按自定义规则对数组进行排序

时间:2020-01-17 17:07:48

标签: arrays swift sorting

我希望按时间对数组进行排序,而不是从0000h到2359h,我希望将其从0600h排序并在0559h结束。下面的代码行按其日期值(日期类型)对警报数组进行排序,但显然是从0000h开始。是否有一种简单的方法可以从某个点进行排序,或者我需要将数组分为两个(一个从早上6点到午夜,一个从午夜到5:59)?

array.sort { $0.time.date.compare($1.time.date) == .orderedAscending }

1 个答案:

答案 0 :(得分:1)

首先扩展"[ec2.Instance(id='i-0ee74643266b26fca')]".split("'") #Makes a list ['[ec2.Instance(id=', 'i-0ee74643266b26fca', ')]'] "[ec2.Instance(id='i-0ee74643266b26fca')]".split("'")[1] #Get the item at position [1] from the list 'i-0ee74643266b26fca' ,以便更轻松地从中提取时分。

Date

然后您可以创建一个自定义排序,如以下post所示:

extension Date {
    var hour: Int { Calendar.current.component(.hour, from: self) }
    var minute: Int { Calendar.current.component(.minute, from: self) }
}

游乐场测试:

array.sort {  
    if $0.time.date.hour < 6, $1.time.date.hour >= 6 { return false }
    if $1.time.date.hour < 6, $0.time.date.hour >= 6 { return true  }
    return ($0.time.date.hour, $0.time.date.minute) < ($1.time.date.hour, $1.time.date.minute)
}