2014-07-06 67 views
16

数组假设我们有排序字典的斯威夫特

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

当我尝试整理使用

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

Xcode中说:“找不到成员标”的阵列。

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

回答

42

错误消息是误导性的。真正的问题是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对象。

1

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

如果时间戳是浮点数: -

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