var arrEmails = NSMutableArray()
arrEmails = ["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"]
上面是我的数组,我想检查是否有重复的值。为此我写了下面的代码。
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
}
}
但是在上面的代码中,如果数组包含如下所示的值,那么它会返回重复值 1。
arrEmails = ["[email protected]", "", "", "[email protected]", "", ""]
我不想删除重复值,我只想检查数组中重复值的数量。 怎样可以检查呢?请帮帮我。
首先停止使用
并使用 Swift 数组。NSMutableArray
所以你有这个数组
let emails = ["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"]
现在您只需输入即可检查是否有重复
let hasDuplicates = emails.count != Set(emails).count
注意,只有当数组的泛型类型为
时,这才有效。Hashable
您的代码计算不同重复项的数量。在您的情况下,所有四个重复项彼此相同 - 即空字符串
""
。
如果要计算具有重复项的对象总数,请将
set.count(for: object)
返回的值相加:
let arrEmails = ["[email protected]", "", "", "[email protected]", "", ""]
let set = NSCountedSet.init(array: arrEmails as! [Any])
let totalDups = set.map { set.count(for: $0) }.filter {$0 > 1}.reduce(0, +)
上面的代码生成
totalDups
of 4
。
用于计算唯一重复项的代码可以减少为一行,如下所示:
let uniqueDups = set.map { set.count(for: $0) }.filter {$0 > 1}.count
SWIFT 4
肯定有更好的方法来做到这一点,但我有一个用来解决此类问题的方法
这已经过测试,您可以将此代码粘贴到 Playground 中以获得即时结果
// here we can store dulicate elements in array
var storeDuplicateValue = [String:Int]()
let arrEmails = ["[email protected]", "", "", "[email protected]", "", "","[email protected]"]
var count = 0
// here we loop through all elements
for email in arrEmails {
if(email != ""){
count = 0
for newEmail in arrEmails {
if(email == newEmail){
count += 1
}
}
// if count is more than 1 we have duplicate elements
if(count > 1){
// so we store duplicate elements in dictionary and its count to know how many times it has been repeated
storeDuplicateValue.updateValue(count, forKey: email)
}
}
}
print(storeDuplicateValue)
// here we get count of keys in dictionary to know number of duplicate strings
print(storeDuplicateValue.keys.count)
你的代码没问题!您得到了正确且预期的结果!
如您的代码中所示,重复的值是“”。
为了更好地理解,您可以更改值数组并重试。
正如大多数其他答案所述,您的代码很好。如果唯一的问题是应该忽略空字符串,您可以在计算重复项之前从数组中过滤掉它们:
let emails = ["[email protected]", "", "", "[email protected]", "", ""]
let emailsWithoutEmptyStrings = emails.filter { $0 != "" }
let set = NSCountedSet(array: emailsWithoutEmptyStrings)
var duplicates = 0
for object in set {
if set.count(for: object) > 1 {
duplicates += 1
}
}
extension Array where Element: Hashable {
var asSet: Set<Element> {
return Set(self)
}
var hasDuplicates: Bool {
return self.count > self.asSet.count
}
}
let someArray = ["kiwi", "mango", "kiwi"]
if someArray.hasDuplicates {
print("has duplicates")
} else {
print("no duplicates")
}