Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
644 views
in Technique[技术] by (71.8m points)

sorting - Sort a Dictionary in Swift

I know that this topic has been already discussed but I can't solve looking other answers, so sorry in advance for my ripetion!

I need to sort this Dictionary by keys

codeValueDict = ["us": "$", "it": "€", "fr": "€"]

so I need a dictionary like this

sortedDict = ["fr": "€", "it": "€", "us": "$"]

but I can't do that.

I tried this

let sortedKeysAndValues = sorted(dictionary) { $0.0 < $1.0 }

but after I need to create two arrays from this dictionary (keys and values) and, using that solution

codesArray = sortedKeysAndValues.keys.array

give me the error '[(String, String)]' does not have a member named 'keys' because that solution doesn't return exactly a dictionary.

So i tried another solution:

    let prova = codiceNomeDict as NSDictionary
    for (k,v) in (Array(codiceNomeDict).sorted {$0.1 < $1.1}) {
        let value = "["(k)": "(v)"]"
        println(value)
    }

Which works good but then I don't know how create a new dictionary of values.

What's the best solution? How to make it works?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The output of sorted function above is an Array. So you cannot get keys & values like a Dictionary. But you can use map function to retrieve those sorted keys & values

Return an Array containing the sorted elements of source{according}. The sorting algorithm is not stable (can change the relative order of elements for which isOrderedBefore does not establish an order).

let codeValueDict = ["us": "$", "it": "€", "fr": "€"]

let sortedArray = sorted(codeValueDict, {$0.0 < $1.0})
print(sortedArray)

let keys = sortedArray.map {return $0.0 }
print(keys)

let values = sortedArray.map {return $0.1 }
print(values)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...