通过数组Swift中的字母生成排序字典

时间:2015-11-16 09:07:20

标签: ios arrays xcode swift dictionary

我有一个部门阵列'名称

var departments: Array<String>!

我想在Dictionary中按字母顺序排序这个数组,例如字典应该是这样的

var MyDictionary = ["A": ["Affenpoo", "Affenpug", "Affenshire", "Affenwich", "Afghan Collie", "Afghan Hound"], "B": ["Bagle Hound", "Boxer"],
    "C": ["Cagle Cound", "Coxer"]]

departments数组不是静态的

如何在swift中生成这个字典?

非常感谢

2 个答案:

答案 0 :(得分:5)

我的方法是迭代数组并获取每个条目的第一个字母。从字母中检索该字母的数组。如果是nil则创建一个新数组。将单词添加到您检索的数组中,然后将数组存储在字典中。

let departments = ["Affenpoo", "Affenpug", "Affenshire", "Affenwich", "Afghan Collie","Cagle Cound", "Coxer"]
var outputDict=[String:[String]]()

for word in departments {
    let initialLetter=word.substringToIndex(word.startIndex.advancedBy(1)).uppercaseString
    var letterArray=outputDict[initialLetter] ?? [String]()
    letterArray.append(word)
    outputDict[initialLetter]=letterArray
}

print(outputDict)
  

[“C”:[“Cagle Cound”,“Coxer”],“A”:[“Affenpoo”,“Affenpug”,“Affenshire”,“Affenwich”,“Afghan Collie”]]

答案 1 :(得分:0)

编辑:Paulw11的解决方案效率更高

我认为这个问题与特别是快速相关,但无论如何都要尝试这个:

let a = ["All", "Cat", "red", "gat", "Star sun", "bet you", "Zeta Fog", "Tea", "Fox"]

let b = a.map{ $0.lowercaseString }

let c = b.sort()
let d = c.map{ $0[$0.startIndex.advancedBy(0)]}

var dictionary:[String:[String]] = [:]
let byInitial = d.map{ initial in

    let clustered = c.filter{$0.hasPrefix("\(initial)")}
    dictionary.updateValue(clustered, forKey:"\(initial)")
}
print("\(dictionary)")