我有两个电话号码集合,我想比较以查看是否有任何匹配。在其他语言中,我循环遍历一个集合,将其添加到需要唯一性的集合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 Maps似乎是一个转换,Dictionaries需要一个值与键一起使用,而且没有明确的&#34; containsKey ()&#34;类型函数,并没有像#34;哈希表&#34;那样的另一个集合。用一种方法来查看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
}
答案 0 :(得分:2)
NSSet会为你工作吗?
func intersectsSet(_ otherSet: NSSet) -> Bool
返回一个布尔值,指示接收集中的至少一个对象是否也存在于另一个给定集中。
您可以从NSSet
创建NSArray
。
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