arrays - Swift - 通过几个比较对数组进行排序
问题描述
我的问题很简单:
- 我的数据库中有很多用户分数(顺便说一下,我正在使用 Firebase)
- 我想得到这些分数(这很容易)并对它们进行排序(不太容易)
如果用户完成锻炼,他将输入他的时间,如果没有,他将输入次数或重复次数。
简单来说,结果对象是这样的:
Result |_ resultValue (Int) // It can be time in seconds or number of reps |_ isFinished (Int) // It can be 0 (not finished) or 1 (finished)
我想像这样对我的结果数组进行排序:
- 第一:isFinished == 1 的所有结果都高于其他结果
- 然后:按 resultValue DESC 对 isFinished == 1 的结果进行排序
- 最后:按 resultValue ASC 对 isFinished == 0 的结果进行排序
我尝试过这样的事情:
self.results = self.results.sorted {
($0.result.isForTimeFinished!, $0.result.resultValue!) >
($1.result.isForTimeFinished!, $1.result.resultValue!)
}
所以未完成的锻炼结果是在锻炼结果完成之后,但是“按结果值 DESC 对 isFinished == 1 的结果进行排序”是不行的......
你知道我怎么能把这一切结合起来吗?
解决方案
尝试这个:
self.results = self.results.sorted {
if $0.result.isForTimeFinished != $1.result.isForTimeFinished {
return $0.result.isForTimeFinished > $1.result.isForTimeFinished
}
else if $0.result.isForTimeFinished == 0 {
return $0.result.resultValue > $1.result.resultValue
}
else {
return $0.result.resultValue < $1.result.resultValue
}
}
注意:我可能有相反的迹象,但玩了一下
推荐阅读
- delphi - 如何在事件处理程序中设置 AnsiString 参数?
- amazon-web-services - 你如何将变量子转换为yaml中的字符串?
- asp.net - 创建一个子域并将其指向域位置
- blazor - 客户端 Blazor HttpClient 工厂
- python - 如何在 Python 中复制 Excel 的 IFERROR
- dialogflow-es - 谷歌操作的文本到语音配置
- python - 在文本中搜索模式中断的模式
- python - 如何将 Python 程序转换为 CLI 而无需键入 python3 来执行?
- android-studio - 使用 Android Studio 和 opencv 的对象检测应用程序
- jetty-9 - 从jetty6迁移时无法在Jetty9中打开httpConnection