ios - (Swift 3)尝试在 swift 3 中按日期对类对象数组进行排序?

标签 ios swift3

我有一个对象数组,其中有一个类型为 Date 的成员,我正在尝试按 Date 对整个数组进行排序,并且排序不正确。 这是我正在使用的代码,数组的名称是 alarms和成员类型的名称 Datetime .

alarms.sort(by: { $0.time.compare($1.time) == .orderedAscending })

每当我对它进行排序时,它都无法正常工作,我正在通过打印 for 中的所有值来测试它循环。

谁能帮我解决这个问题的语法?

最佳答案

compareNSDate功能。与 Date你可以只使用 <运算符(operator)。例如:

alarms.sort { $0.time < $1.time }

话虽如此,compare不过也应该有效。我怀疑这里有一些更深层次的问题,也许是你的 time值有不同的日期。您可能只查看时间部分,但在比较 Date 时对象,它同时考虑日期和时间。如果您只想查看时间部分,有几种方法可以做到这一点,例如,查看 time 之间的时间间隔。和一天的开始:

let calendar = Calendar.current

alarms.sort {
    let elapsed0 = $0.time.timeIntervalSince(calendar.startOfDay(for: $0.time))
    let elapsed1 = $1.time.timeIntervalSince(calendar.startOfDay(for: $1.time))
    return elapsed0 < elapsed1
}

有很多方法可以做到这一点,但希望这能说明这个想法。

关于ios - (Swift 3)尝试在 swift 3 中按日期对类对象数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39605279/

相关文章:

ios - 在 UITableViewController 中处理多个计时器值?

ios - 无法在 swift 3 中获取 jsondata?

ios - 如何在 Swift 中使用 query.whereKey 检查 UISearchBar 是否返回结果

objective-c - Objective-C : Getting 'Invalid Initializer Error' when setting CLLocationCoordinate2D location

iOS : how to use an asset with a shadow as a button image and make the shadow part not tappable?

ios - 为什么对成员 'Subscript' 的引用不明确?

ios - 完成处理程序 Swift 3

ios - UITableView - 我们正在考虑无意折叠并改用标准高度

ios - 此方法中的泄漏

ios - 如何使用 SWXMLHash 反序列化 NSDate