我不确定我是否正确地提出了这个问题。但这是解释:我有一个联系人词典:
var arrOfDictContacts = NSMutableArray()
self.arrOfDictContacts.addObject(["\(names)":"\(numb)"])
追加
后arrOfDictContacts = ["Arun":"+123", "Babu":"+234", "Chitra":"+345"]
我有一组名字arrOfNames = ["Arun", "Chitra"]
现在我想在这样的数组中使用dict中这些名称的相应数量:
arrOfNumbers = ["+123", "+345"] // Expected Output
我该如何获取它们?
答案 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)")
以下是输出在游乐场中的样子:
我认为您最好在Swift中了解有关map
,filter
,...的更多信息。如果语言提供了优雅的方式来做某事,请确保使用它而不是重新发明轮子。
答案 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] })