(Swift 3) 试图在 Swift 3 中按日期对类对象数组进行排序? [英] (Swift 3) Trying to sort an array of class objects by Date in swift 3?
问题描述
我有一个对象数组,其成员类型为 Date
,我试图按 Date
对整个数组进行排序,但排序不正确.这是我使用的代码,数组的名字是alarms
,成员类型Date
的名字是time
.>
I have an array of objects that has a member that is type Date
, and I'm trying to sort the whole array by Date
, and it's not sorting correctly.
This is the code I'm using, the name of the array is alarms
and the name of the member type Date
is time
.
alarms.sort(by: { $0.time.compare($1.time) == .orderedAscending })
每当我对它进行排序时,它都无法正常工作,我正在通过在 for
循环中打印所有值来测试它.
and whenever I sort it it just doesn't work correctly, and I'm testing it by printing all the values in a for
loop.
有人可以帮我解决这个问题的语法吗?
Can someone help me with the syntax for this?
推荐答案
compare
是一个 NSDate
函数.使用 Date
您可以只使用 <
运算符.例如:
The compare
is a NSDate
function. With Date
you can just use <
operator. For example:
alarms.sort { $0.time < $1.time }
<小时>
话虽如此,compare
也应该有效.我怀疑这里有一些更深层次的问题,也许你的 time
值有不同的日期.您可能只查看时间部分,但在比较 Date
对象时,它会同时考虑日期和时间.如果您只想查看时间部分,有几种方法可以做到,例如,查看 time
和一天开始之间的时间间隔:
Having said that, compare
should work, too, though. I suspect there's some deeper issue here, that perhaps your time
values have different dates. You might only be looking at the time portion, but when comparing Date
objects, it considers both the date and time. If you only want to look at the time portion, there are several ways of doing that, for example, look at the time interval between time
and the start of the day:
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
}
有很多方法可以做到这一点,但希望这能说明这个想法.
There are lots of ways to do this, but hopefully this illustrates the idea.
这篇关于(Swift 3) 试图在 Swift 3 中按日期对类对象数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!