gpt4 book ai didi

swift - 从 Array> 中提取字符串数组的有效方法

转载 作者:可可西里 更新时间:2023-11-01 00:57:28 24 4
gpt4 key购买 nike

是否有一种有效的方法可以在不使用嵌套 for 循环的情况下从下面的 AllData 中获取包含“名称”字符串的数组?我得到的代码有效:“Alice”、“Brad Smith MD”、“Dr. 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)
}

最佳答案

绝对没有理由遍历字典中的一组 (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),但是 struct 方法的开销更低,样板代码更少,并且可以让您轻松处理非 String 员工数据。

关于swift - 从 Array<Dictionary<String,String>> 中提取字符串数组的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42637851/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com