如何在Swift 2.0中获取数组中值集的dict值?

时间:2015-09-19 02:52:26

标签: ios arrays nsdictionary swift2

我不确定我是否正确地提出了这个问题。但这是解释:我有一个联系人词典:

var arrOfDictContacts = NSMutableArray()
self.arrOfDictContacts.addObject(["\(names)":"\(numb)"])

追加

arrOfDictContacts = ["Arun":"+123", "Babu":"+234", "Chitra":"+345"]

我有一组名字arrOfNames = ["Arun", "Chitra"]

现在我想在这样的数组中使用dict中这些名称的相应数量:

arrOfNumbers = ["+123", "+345"] // Expected Output 我该如何获取它们?

4 个答案:

答案 0 :(得分:1)

你可以这样做:

var arrOfDictContacts = Dictionary<String, String>()
arrOfDictContacts = ["Arun":"+123", "Babu":"+234", "Chitra":"+345"]
var arrOfNames = ["Arun", "Chitra"]
var arrOfContacts = [String]()

for name in arrOfNames {
    arrOfContacts.append(arrOfDictContacts[name]!)
}

println("\(arrOfContacts)")

答案 1 :(得分:0)

请试试这个:

    let dict = ["Arun":"+123", "Babu":"+234", "Chitra":"+345"]
    let names = ["Arun", "Babu"]

    let allValues = dict.map({ $1 })
    let valuesByName = names.map({ dict[$0] })

    print("\(allValues)")
    print("\(valuesByName)")

以下是输出在游乐场中的样子:

enter image description here

我认为您最好在Swift中了解有关mapfilter,...的更多信息。如果语言提供了优雅的方式来做某事,请确保使用它而不是重新发明轮子。

答案 2 :(得分:0)

你去......

let arrOfDictContacts = ["Arun":"+123", "Babu":"+234", "Chitra":"+345"]
let arrOfNames = ["Arun", "Chitra"]
var arrOfNumbers = [String]()

for name in arrOfNames {

 if let aNumber = arrOfDictContacts[name] {

    arrOfNumbers.append(aNumber);
 }
}

答案 3 :(得分:0)

这是一个单行:

arrOfNames.map({ arrOfDictContacts[$0] })