简体   繁体   中英

Generate Sorted Dictionary by Letters from an Array Swift

I have an Array of Departments' Names

var departments: Array<String>!

I want to sort this array alphabetically in Dictionary eg the dictionary should be like this

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

the departments array is not static

how can i generate this dictionary in swift?

Thanks a lot

My approach would be to iterate the array and take the first letter of each entry. Retrieve the array from the dictionary for that letter. If it is nil create a new array. Add the word to the array you retrieved and then store the array in the dictionary.

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"]]

EDIT: solution by Paulw11 is more efficient

I don't think this question is relevant to swift in particular, but anyways try this:

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)")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM