我有兩個電話號碼集合,我想比較一下,看看是否有任何匹配。在其他語言中,我經歷了一個集就不斷循環,把它添加到需要獨特的集合變種類型,遍歷和其他檢查如火柴:Swift是否有一個獨特的無序值集合的概念?
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似乎是一種轉換,字典需要使用鍵值,並且沒有明確的「containsKey()」類型函數,並且似乎沒有其他集合,例如「hash表「的方法,看看是否有一個變種在那裏。 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
}
還比較[如何在Swift中創建唯一對象列表數組](http://stackoverflow.com/questions/24044190/how-to-create-array-of-unique-object-list-in -迅速)。一些答案顯示瞭如何在純Swift中實現集合類型。 – 2014-11-09 00:22:06
Swift 1.2現在有一個本地Set類型,比較http://stackoverflow.com/a/28426765/1187415。 – 2015-02-10 08:28:58