在Swift中对字典数组进行排序

17

假设我们有

var filesAndProperties:Dictionary<String, Any>[]=[] //we fill the array later

当我尝试使用排序数组时

filesAndProperties.sort({$0["lastModified"] > $1["lastModified"]})

Xcode显示“找不到成员下标”。

我如何按照特定键中的值对这样的字典数组进行排序?

2个回答

43
错误消息有误导性。真正的问题是Swift编译器不知道$0["lastModified"]对象的类型以及如何进行比较。 因此,你需要更加明确,例如:
filesAndProperties.sort {
    item1, item2 in
    let date1 = item1["lastModified"] as Double
    let date2 = item2["lastModified"] as Double
    return date1 > date2
}

如果时间戳是浮点数,或者

filesAndProperties.sort {
    item1, item2 in
    let date1 = item1["lastModified"] as NSDate
    let date2 = item2["lastModified"] as NSDate
    return date1.compare(date2) == NSComparisonResult.OrderedDescending
}

如果时间戳是 NSDate 对象。


2

在这里,问题是编译器无法理解对象$0["lastModified"]的类型。

如果时间戳是浮点数:

filesAndProperties = filesAndProperties.sorted(by: {
                (($0 as! Dictionary<String, AnyObject>)["lastModified"] as? Double)! < (($1 as! Dictionary<String, AnyObject>)["lastModified"] as? Double)!
            })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接