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

时间:2022-06-15 16:00:04

Suppose we have

假设我们有

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

When I try sorting the array using

当我尝试使用排序数组

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

Xcode says "could not find member subscript".

Xcode说“无法找到成员下标”。

How do I sort an array of such dictionaries by values in a specific key?

如何按特定键中的值对这些词典数组进行排序?

2 个解决方案

#1


42  

The error message is misleading. The real problem is that the Swift compiler does not know what type of object $0["lastModified"] is and how to compare them.

错误消息具有误导性。真正的问题是Swift编译器不知道对象$ 0 [“lastModified”]是什么类型的对象以及如何比较它们。

So you have to be a bit more explicit, for example

例如,你必须更明确一些

filesAndProperties.sort {
    item1, item2 in
    let date1 = item1["lastModified"] as Double
    let date2 = item2["lastModified"] as Double
    return date1 > date2
}

if the timestamps are floating point numbers, or

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

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

if the timestamps are NSDate objects.

如果时间戳是NSDate对象。

#2


1  

Here, The problem is that compiler unable to understand type that what of object $0["lastModified"] is.

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

if the timestamps are floating point numbers:-

如果时间戳是浮点数: -

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

#1


42  

The error message is misleading. The real problem is that the Swift compiler does not know what type of object $0["lastModified"] is and how to compare them.

错误消息具有误导性。真正的问题是Swift编译器不知道对象$ 0 [“lastModified”]是什么类型的对象以及如何比较它们。

So you have to be a bit more explicit, for example

例如,你必须更明确一些

filesAndProperties.sort {
    item1, item2 in
    let date1 = item1["lastModified"] as Double
    let date2 = item2["lastModified"] as Double
    return date1 > date2
}

if the timestamps are floating point numbers, or

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

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

if the timestamps are NSDate objects.

如果时间戳是NSDate对象。

#2


1  

Here, The problem is that compiler unable to understand type that what of object $0["lastModified"] is.

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

if the timestamps are floating point numbers:-

如果时间戳是浮点数: -

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