是否有一种有效的方法可以在不使用嵌套for循环的情况下从AllData获取包含“names”字符串的Array?我得到的代码是:“Alice”,“Brad Smith MD”,“Quam博士”,“Jennifer Johnson”,“John Banks MD”作为输出,但我想在没有嵌套for循环的情况下这样做,因为它不是很有效O n ^ 2而且难以阅读?我在Xcode 8.2中使用Swift 3
var AllData:Array<Dictionary<String,String>> = []
override func viewDidLoad() {
super.viewDidLoad()
AllData = [["pic":"Alice.png","name":"Alice Smith","position":"Nurse"],
["pic":"brad.png","name":"Brad Smith MD","position":"Primary Doctor"],
["pic":"user.png","name":"Dr. Quam","position":"Immunologist"],
["pic":"jennifer.jpg","name":"Jennifer Johnson","position":"Case Manager"],
["pic":"user.png","name":"John Banks MD","position":"Cardiologist"]
]
let names = ""
for thing in AllData { //thing is pic, name, position
for (key, value) in thing {
if(key == "name"){
names.append(value)
//print(value)
}
}
}
print(names)
}
答案 0 :(得分:3)
绝对没有理由在字典中迭代一组(key, value)
对,比较键直到找到特定匹配,只使用该值。只需直接下标字典:
var names = ""
for dict in AllData { //thing is pic, name, position
guard let name = dict["name"] else { continue }
names.append(name)
}
print(names)
功能方法更快更简单:
let names = AllData.flatMap{ $0["name"] }.joined(separator: "")
此外,您不应使用Dictionary
来存储具有静态密钥集的数据。如果使用结构或类来封装数据,那么您将拥有更简单,更快速且更安全的代码。最终结果看起来像这样:
struct Employee {
let pic: String
let name: String
let position: Sting //TODO: would this be better as an enum?
}
class MyVC: UIViewController {
//...
let employees = [
Employee(
pic: "Alice.png",
name: "Alice Smith",
position: "Nurse"
),
Employee(
pic: "brad.png",
name: "Brad Smith MD",
position: "Primary Doctor"
),
Employee(
pic: "user.png",
name: "Dr. Quam",
position: "Immunologist"
),
Employee(
pic: "jennifer.jpg",
name: "Jennifer Johnson",
position: "Case Manager"
),
Employee(
pic: "user.png",
name: "John Banks MD",
position: "Cardiologist"
)
]
override func viewDidLoad() {
super.viewDidLoad()
let names = employees.map{ $0.name }.joined(separator: "")
print(names)
}
//...
}
dict和struct方法都是O(employees.count)
,但结构方法的开销较低,样板代码较少,并且可以让您轻松处理非String
员工数据。