gpt4 book ai didi

ios - 如何检查数组中是否有重复值?

转载 作者:搜寻专家 更新时间:2023-11-01 06:01:38 25 4
gpt4 key购买 nike

var arrEmails = NSMutableArray()
arrEmails = ["a.a@gmail.com", "a.a1@gmail.com", "a.a@gmail.com", "b.b@gmail.com", "c.c@gmail.com", "a.a1@gmail.com"]

上面是我的数组,我想检查是否有重复值。为此,我写了下面的代码。

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 = ["a.a@gmail.com", "", "", "b.b@gmail.com", "", ""]

我不想删除重复值,我只想检查数组中重复值的数量。怎么查?请帮助我。

最佳答案

First of all stop using NSMutableArray and use Swift array.

所以你有这个数组

let emails = ["a.a@gmail.com", "a.a1@gmail.com", "a.a@gmail.com", "b.b@gmail.com", "c.c@gmail.com", "a.a1@gmail.com"]

现在你可以简单的写检查是否有重复

let hasDuplicates = emails.count != Set(emails).count

Note, this does work only if the generic type of the array is Hashable.

关于ios - 如何检查数组中是否有重复值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48238184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com