PhilHarmonie PhilHarmonie - 6 months ago 46
Swift Question

Swift 2 - Sort Dictionary with NSDate()-Keys

I want to sort this kind of Dictionary:

var data = [NSDate: [String: AnyObject]]()


e.g.

data: [2015-08-29 12:08:29 +0000: ["foo": "bar"]],
[2015-08-29 12:05:13 +0000: ["foo": "bar"]],
[2015-08-29 12:11:02 +0000: ["foo": "bar"]]


should then be:

dataSorted: [2015-08-29 12:05:13 +0000: ["foo": "bar"]],
[2015-08-29 12:08:29 +0000: ["foo": "bar"]],
[2015-08-29 12:11:02 +0000: ["foo": "bar"]]


I tried:

let dataSorted = Array(data.keys).sorted(<)
// Could not find an overload for '<' that accepts the supplied arguments


and

let dataSorted = sorted(data) { $0.0 < $1.0 }
// Could not find member '0'

Answer

You cannot sort dictionaries as they do not have order, so I use array in my answer instead.

By default NSDate does not conform to Comparable protocol. You have to use compare method:

let results = Array(data).sort({ $0.0.compare($1.0) == .OrderedAscending })

This extension can be used to make NSDate conform to Comparable:

extension NSDate: Comparable {}
public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.compare(rhs) == .OrderedSame
}

public func >(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.compare(rhs) == .OrderedDescending
}

public func <(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.compare(rhs) == NSComparisonResult.OrderedAscending
}

public func <=(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs < rhs || lhs == rhs
}

public func >=(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs > rhs || lhs == rhs
}

Then you can simply use:

let results = Array(data).sort({ $0.0 < $1.0})
Comments