gpt4 book ai didi

swift - 将项目作为字典值添加到数组

转载 作者:行者123 更新时间:2023-11-30 11:51:56 25 4
gpt4 key购买 nike

我正在尝试找出 Swift 中向 Array 添加值的最佳方法,该数组是 Value 中的 >字典。我想建立一个联系人字典,按名字的第一个字母排序。例如 [A : [Aaron、Adam 等...]、B : [Brian、Brittany 等...]、...]

我发现了这个功能:

updateValue(_:forKey:)

并尝试在循环中使用它:

for contact in self.contacts.sorted() {
self.contactDictionary.updateValue([contact], forKey: String(describing: contact.characters.first))
}

但是当我尝试使用它时,它用新数组替换了现有数组。我知道我可以手动检查字典中的键是否存在,如果存在,检索数组然后附加一个新值,否则添加新的键/值对,但我不确定 Swift 是否提供了更简单的/更好的方法来做到这一点。

任何见解将不胜感激!

最佳答案

您可以使用reduce(into:)方法(Swift4),如下所示:

let contacts = ["Aaron", "Adam", "Brian", "Brittany", ""]
let dictionary = contacts.reduce(into: [String:[String]]()) { result, element in
// make sure there is at least one letter in your string else return
guard let first = element.first else { return }
// create a string with that initial
let initial = String(first)
// initialize an array with one element or add another element to the existing value
result[initial] = (result[initial] ?? []) + [element]
}
print(dictionary) // ["B": ["Brian", "Brittany"], "A": ["Aaron", "Adam"]]
<小时/>

如果您使用的是 Swift3 或更早版本,您需要在闭包内创建一个可变结果字典:

let contacts = ["Aaron", "Adam", "Brian", "Brittany", ""]
let dictionary = contacts.reduce([String:[String]]()) { result, element in
var result = result
guard let first = element.first else { return result }
let initial = String(first)
result[initial] = (result[initial] ?? []) + [element]
return result
}
print(dictionary) // ["B": ["Brian", "Brittany"], "A": ["Aaron", "Adam"]]
<小时/>

请注意,结果未排序。字典是一个无序的集合。如果您需要对字典进行排序并返回(键,值)元组数组,您可以使用按键排序,如下所示:

let sorted = dictionary.sorted {$0.key < $1.key}
print(sorted)

"[(key: "A", value: ["Aaron", "Adam"]), (key: "B", value: ["Brian", "Brittany"])]\n"

关于swift - 将项目作为字典值添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48257031/

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