Swift 2 - 使用NSDate()排序字典 - 键

时间:2015-08-29 12:48:37

标签: arrays swift sorting dictionary swift2

我想对这种词典进行排序:

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"]]

应该是:

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"]]

我试过了:

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

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

2 个答案:

答案 0 :(得分:4)

你不能对字典进行排序,因为它们没有顺序,所以我在答案中使用数组。

默认情况下,NSDate不符合Comparable协议。您必须使用compare方法:

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

此扩展程序可用于使NSDate符合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
}

然后你可以简单地使用:

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

答案 1 :(得分:1)

一个(至少对我而言)更容易阅读的解决方案,没有$ 0的东西将是:

let kartoffel = data.keys.sort { (date, date2) in   
        return date.compare(date2) == NSComparisonResult.OrderedAscending
    }