var arrEmails = NSMutableArray()
arrEmails = ["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"]
above is my Array and i want to check is there any duplicate value or not. and for that i write below code.
let set = NSCountedSet.init(array: arrEmails as! [Any])
var duplicates: Int = 0
for var object in set {
if set.count(for: object) > 1 {
duplicates = duplicates+1
}
}
but in above code, if array contains values like below than it returns me duplicates value 1.
arrEmails = ["[email protected]", "", "", "[email protected]", "", ""]
I don't want to remove duplicate value, i just want to check number of duplicate value in array. How can check? please help me out.
First of all stop using
NSMutableArrayand use Swift array.
So you have this array
let emails = ["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"]
Now you can check whether there are duplicates simply writing
let hasDuplicates = emails.count != Set(emails).count
Note, this does work only if the generic type of the array is
Hashable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With