Alex Dufetel
Alex Dufetel

Reputation: 101

Problems sorting an Array

I am trying to sort an Array used to populate a TableView.

My data is structured as following :

var data = [[Double:String]]()

ex : [[1450051409873: "foo"], [1450051409874: "bar"], [1450051409875: "baz"]]

I want my data to be sorted by the value of the doubles (i.e. 1450051409873...)

I am doing the following to sort my data: data.sortInPlace({$0[0] > $1[0]})

This does not appear to work.

Upvotes: 1

Views: 54

Answers (1)

Nate Cook
Nate Cook

Reputation: 93276

That's a dictionary, not an array. If you'd like to access the values sorted by the keys, you can create a sorted array of the keys, then access the values one at a time:

var data: [Double:String] = [1450051409873: "foo", 1450051409874: "bar", 1450051409875: "baz"]
var sortedKeys = data.keys.sort()
for key in sortedKeys {
    print(data[key]!)
}
// foo
// bar
// baz

Or you can directly compute the sorted values by providing a closure to sort:

var sortedValues = data.sort({ lhs, rhs in
    lhs.0 < rhs.0
}).map({ $0.1 })
// sortedValues == ["foo", "bar", "baz"]

Upvotes: 3

Related Questions