首页 > 解决方案 > Swift - 通过几个比较对数组进行排序

问题描述

我的问题很简单:

如果用户完成锻炼,他将输入他的时间,如果没有,他将输入次数或重复次数。

简单来说,结果对象是这样的:

Result
 |_ resultValue (Int) // It can be time in seconds or number of reps
 |_ isFinished (Int) // It can be 0 (not finished) or 1 (finished)

我想像这样对我的结果数组进行排序:

  1. 第一:isFinished == 1 的所有结果都高于其他结果
  2. 然后:按 resultValue DESC 对 isFinished == 1 的结果进行排序
  3. 最后:按 resultValue ASC 对 isFinished == 0 的结果进行排序

我尝试过这样的事情:

self.results = self.results.sorted {
 ($0.result.isForTimeFinished!, $0.result.resultValue!) > 
 ($1.result.isForTimeFinished!, $1.result.resultValue!)
}

所以未完成的锻炼结果是在锻炼结果完成之后,但是“按结果值 DESC 对 isFinished == 1 的结果进行排序”是不行的......

你知道我怎么能把这一切结合起来吗?

标签: arraysswiftfirebasesortingswift3

解决方案


尝试这个:

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
    }
}

注意:我可能有相反的迹象,但玩了一下


推荐阅读