1

I am trying to get an array o keys from a dictionary where the array is sorted by values. For example:

//dictionary contains [alpha:C],[beta:A],[gamma:B]

My array should return:

//[beta, gamma, alpha]

I tried:

let keys = Array(myDictionary.keys).sort({ (a,b) -> Bool in
        a.compare(b) == .OrderedAscending
    })

but this returns the order by keys:

//[alpha, beta, gamma]

1 Answer 1

2

Given your dictionary

let dict = ["alpha":"C","beta":"A","gamma":"B"]

You can sort the keys by value with this code

let keysSortedByValue = dict.sort { $0.1 < $1.1 }.map { $0.0 }

// ["beta", "gamma", "alpha"]

Update

This screenshot to answer to your comment below

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

Although i clicked "accepted" there is something that i don't understand. This: let dict = ["alpha":"alpha","beta":"beta","gamma":"gamma"] returns first beta then alpha and the gamma. It seems your advise does not work with strings properly
@Mic: I just tested it and it is returning ["alpha", "beta", "gamma"]. Please see the screenshot I added to my answer. Are you sure you are using exactly this input? I suspect you are using some uppercase letters...
You was correct. Because of many tests there was a 0 instead of 1 and I missed. Answer is accepted. Sorry for this. In case I gona use uppercase letters is something that I have to mind?
@Mic: if you want case-insensitive String sorting, you could apply lowerCaseString to the arguments in the sorting closure, e.g. let keysSortedByValue = dict.sort { $0.1.lowercaseString < $1.1.lowercaseString }.map { $0.0 }.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.