1

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.

0

1 Answer 1

3

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"]
Sign up to request clarification or add additional context in comments.

Comments

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.