To find a unique value of array from a normal array is very easy in Swift.
Let's get started :
I have mentioned code below. use it and life will be easy. but I would like to recommend you to please dont copy and paste code to your project. try to write your code and your logic in your project.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Created by : Kumar Lav. | |
//Simply Create an Extension of Array with element of type Equatable. | |
// And Inside that create a method who will be sort your current Array elements with a unique element. | |
// We just have to use some Hack of Swift. | |
extension Array where Element:Equatable{ | |
func getUniqueArray()-> [Element]{ | |
var result = [Element]() | |
for value in self | |
{ | |
if result.contains(value) == false | |
{ | |
result.append(value) | |
} | |
} | |
return result | |
} | |
} | |
// Now Test with Playground of your Xcode. | |
// I would like to recommend you to use Playground for logic. | |
let normalArray = [1,8,44,2,3,1,2,4,5,3,2,2,4,5,1] | |
// Now use our method which we created. | |
var uniqueArray = normalArray.getUniqueArray() | |
print("Unique Array::",uniqueArray) | |
// Output Will be => Unique Array:: [1, 8, 44, 2, 3, 4, 5] | |
// if you want to sort Unique Array than use Sort method | |
// Assending and Desending Order depends on you. What you wants. | |
uniqueArray.sort(by:<) | |
print("Sorted Unique Array::",uniqueArray) | |
// Output will be => Sorted Unique Array:: [1, 2, 3, 4, 5, 8, 44] | |
// NOTE: | |
// you can use this method for all kind of elements like: Int, String, Double etc. | |
Comments
Post a Comment