gpt4 book ai didi

ios - Swift 是否有唯一无序值集合的概念?

转载 作者:行者123 更新时间:2023-11-28 05:32:59 27 4
gpt4 key购买 nike

我有两个电话号码集合,我想比较它们是否匹配。在其他语言中,我会循环遍历一个集合,将其添加到需要唯一性的集合 var 类型中,循环遍历另一个集合并检查匹配项,例如:

var phones = ["1","2","3"]
var phones2 = ["2","5","6"]
var uniqueCollection: Set = Set()
for var i = 0; i < phones.count; i++ {
if (uniqueCollection.containsKey(phones[i]) == false){
uniqueCollection.add(phones[i])
}
}
var anyMatch = false
for var j = 0; j < phones2.count; j++{
if uniqueCollection.containsKey(phones2[j]) {
anyMatch = true
}
}

到目前为止,我还没有找到任何方法来做到这一点,因为 Swift map 似乎是一种转换,字典需要一个值来与键一起使用,并且没有明确的“containsKey()”类型函数,并且似乎没有像“哈希表”这样的另一个集合,它有一种方法可以查看其中是否有 var。 http://www.weheartswift.com/higher-order-functions-map-filter-reduce-and-more/

http://nshipster.com/swift-comparison-protocols/

假设这不存在,我打算只采用双循环的长路,如果有两个大型集合,这将降低性能。

func checkMultisAnyMatch(personMultis: [[AnyObject]], parseMultis: [[AnyObject]]) -> Bool{
//Put all the phone #'s or emails for the person into an Array
//Put all the phone #'s or emails for the PF contact into an array
//Loop through the phones in the parseContact
//if any match, break the loop, and set anyPhoneMatch = true
var anyMatch = false
for var i = 0; i < personMultis.count; i++ {
//order is Id, label, value, type
//that means it's in the 3rd column, or #2 subscript
var personMulti:AnyObject? = personMultis[i][2]
if (personMulti != nil) {
for var j = 0; j < parseMultis.count; j++ {
//order is Id, label, value, type
var parseMulti:AnyObject? = parseMultis[j][2]
if parseMulti != nil {
if parseMulti! as NSString == personMulti! as NSString {
anyMatch = true
}//if 4
}//if 3
}//for 2
}//if
}//for
return anyMatch
}

最佳答案

NSSet 适合你吗?

func intersectsSet(_ otherSet: NSSet) -> Bool
返回一个 bool 值,指示接收集中的至少一个对象是否也存在于另一个给定集中。

您可以从 NSArray 创建一个 NSSet

var set1 = NSSet(array:["number1", "number2", "number3"])
var set2 = NSSet(array:["number4", "number2", "number5"])
var set3 = NSSet(array:["number4", "number5", "number6"])


let contains1 = set1.intersectsSet(set2) // true
let contains2 = set1.intersectsSet(set3) // false

关于ios - Swift 是否有唯一无序值集合的概念?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26823519/

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