-1

It is my dictionary:

var _dict :[String:String]=[
            "a":"h1",
            "b":"b1",
            "c":"j1",
            "e":"o1",
            "f": "m1",
            "g":"u1",
            "h":"r1"
        ]

And I am trying to sort it by value like this:

_dict = _dict.sort({ $0.1 > $1.1 })

But I get this error message:

Cannot invoke 'sort' with an argument list of type '(@noescape ((String, String), (String, String)) -> Bool)'

Maysam
  • 7,246
  • 13
  • 68
  • 106
  • 2
    A dictionary is an unordered collection type by definition and therefore cannot be sorted. – vadian Feb 20 '16 at 15:41
  • @Maysam no need to create an Array of tuples. If you sort the dictionary itself the result will be naturally an array of tuples. – Leo Dabus Feb 20 '16 at 17:08

2 Answers2

3

There is no such thing as sorting a dictionary. A dictionary is unordered. You'll have to think of something else you'd like to do, such as making an array of tuples and sorting that.

Example:

var arr = Array(_dict)
arr = arr.sort{ $0.1 > $1.1 }
matt
  • 515,959
  • 87
  • 875
  • 1,141
0

Dictionary id unordered but what you could to get sorted keys and values is:

var _dict :[String:String]=[
"a":"h1",
"b":"b1",
"c":"j1",
"e":"o1",
"f": "m1",
"g":"u1",
"h":"r1"
]
//get the keys and sort them.
let keysAndValues = _dict.keys.sort().map { ($0, _dict[$0]!) }

Dict is now transformed into array of tuples, where first element of tuple is key, and second is value.

kacperh
  • 143
  • 1
  • 6