我有一个字典的NSMutableArray。
dic1 = ["user":"Smith","points":12,"lastPoints":4,online:3MonthsAgo(NSDate)]
dic2 = ["user":"Mike","points":22,"lastPoints":3,online:2MonthsAgo(NSDate)]
dic3 = ["user":"Mark","points":22,"lastRank":5,online:now(NSDate)]
dic4 = ["user":"Jay","points":16,"lastPoints":2,online:2minutes(NSDate)]
dic5 = ["user":"Alex","points":13,"lastPoints":5,online:1hr(NSDate)]
dic6 = ["user":"Peter","points":22,"lastPoints":3,online:2days(NSDate)]
我想用3种方式重新武装这个, 具有最高分的第一批用户将首先显示 所以
Mike:22
Mark:22
Peter:22
Jay:16
Alex:13
Smith:12
现在我确实使用了
let sort = NSSortDescriptor(key: "points", ascending: false)
我想要做的下一件事再次根据 lastPoints 示例
对这些用户进行排序Mark:22:5
Mike:22:3
Peter:22:3
Jay:16:2
Alex:13:5
Smith:12:4
然后根据他们的最后在线日期对迈克和彼得在阵列中的位置进行排序。 现在,当我尝试
let sortAgain = NSSortDescriptor(key: "lastPoints", ascending: false) and then
let sortAgain2 = NSSortDescriptor(key: "online", ascending: false)
删除之前我做过的那种积分,并根据lastPoints再次对所有内容进行排序。 我希望它根据点进行排序,然后查看点是否相等,根据lastPoints对这些点数据进行排序。如果lastPoints相等,那么这些相等的数据依赖于" Online"日期。
答案 0 :(得分:1)
试试这个:
let result = arr.sort {
let p0 = $0["points"] as! Int
let p1 = $1["points"] as! Int
let lp0 = $0["lastPoints"] as! Int
let lp1 = $1["lastPoints"] as! Int
let online0 = $0["online"] as! NSDate
let online1 = $1["online"] as! NSDate
if p0 != p1 {
return p0 > p1
} else if lp0 != lp1 {
return lp0 > lp1
} else {
return online0.timeIntervalSince1970 > online1.timeIntervalSince1970
}
}
答案 1 :(得分:0)
我建议使用sort
(或sortInPlace
)函数,您可以在其中指定自定义排序块。例如,如果您将所有Dictionaries
放入Array
,则可以执行以下操作:
array.sort { (dict1, dict2) -> Bool in
if let p1 = dictionary1["points"] as? Int, let p2 = dictionary2["points"] as? Int {
if let l1 = dictionary1["lastPoints"] as? Int, let l2 = dictionary2["lastPoints"] as? Int where p1 == p2 {
return l1 > l2
}
return p1 > p2
}
return false
}
你必须自己做一个合适的实现,但这个概念应该适合你。