Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 575
Matte.Car Avatar asked May 05 '15 13:05

Matte.Car


People also ask

How do you sort a dictionary in Swift?

You can't sort a dictionary, it's an associative container. If you need a particular order, copy keys into an array, and sort them. Then iterate over the keys, and pull their corresponding values. @dasblinkenlight So can you tell me that how to sort an array in swift?

How do you sort a dictionary by value in Swift?

Swift Dictionary sorted() The sorted() method sorts a dictionary by key or value in a specific order (ascending or descending).

Is Swift dictionary ordered?

There is no order. Dictionaries in Swift are an unordered collection type. The order in which the values will be returned cannot be determined.


1 Answers

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)
like image 126
Duyen-Hoa Avatar answered Sep 21 '22 17:09

Duyen-Hoa