Pac*_*ong 4 arrays dictionary ios swift
我有一个数组,例如["Apple", "Banana", "Blueberry", "Eggplant"],我想将其转换为如下字典:
[
"A" : ["Apple"],
"B" : ["Banana", "Blueberry"],
"C" : [],
"D" : [],
"E" : ["Eggplant"]
]
Run Code Online (Sandbox Code Playgroud)
我在Xcode 7 beta 4上使用Swift 2.谢谢!
仅使用Swift 2对象和方法,并使用字母表中每个字母的键:
let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".characters.map({ String($0) })
let words = ["Apple", "Banana", "Blueberry", "Eggplant"]
var result = [String:[String]]()
for letter in alphabet {
result[letter] = []
let matches = words.filter({ $0.hasPrefix(letter) })
if !matches.isEmpty {
for word in matches {
result[letter]?.append(word)
}
}
}
print(result)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3489 次 |
| 最近记录: |