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

标签 ios swift

我有两个电话号码集合,我想比较它们是否匹配。在其他语言中,我会循环遍历一个集合,将其添加到需要唯一性的集合 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/

相关文章:

ios - 如何从 iOS 中的 Google Maps clustermanager 获取所有项目

ios - UIKit 是否有用于上下文弹出窗口的类?

ios - UICollectionView 必须使用非 nil 布局参数初始化为 Subview

ios - 重用动态 TableView 单元格,而无需在 Controller 中维护每个单元格的状态

ios - 如何在带有动画的图像之间切换?

ios - 模态对话框的按钮失败

ios - 如何识别节标题 View 的节号

ios - 错误 : Initializer for optional binding must have Optional type, 不是 'DetailViewController'

swift - 如何判断 facebook 和 gmail firebase 用户是否已创建

iPhone SDK : Tag friends in Post using Facebook Graph API