(Swift 3) Trying to sort an array of class objects

2019-06-15 12:48发布

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

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?

标签: ios swift3
1条回答
Root(大扎)
2楼-- · 2019-06-15 13:16

The compare is a NSDate function. With Date you can just use < operator. For example:

alarms.sort { $0.time < $1.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.

查看更多
登录 后发表回答