您可以使用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)
“ [[(键:” A“,值:[” Aaron“,”亚当“]),(键:” B“,值:[” Brian“,” Brittany“])] \ n”