【Swift】Swift3から日付比較(Date)に演算子が扱えるみたいだった
Swift3で日付比較したい場面に出くわして、
いつものようにDateのcompare
あたりを使おうとしてたら、
いつものようにNSComparisonResult(とくにorderedAscending
とorderedDescending
)でどちらがa < b、a < bとかがわからなくなって確認してたら....
とある記事で、
日付の比較に比較演算子が使えるのを今更しったわけです...
それもSwift3かららしく.....今更ながらお恥ずかしい😓
ってなわけで、さっそく使ってみる。
やること
- 簡単な3つの日付を配列
dates
に加えて、それを降順で並び替える。
let calendar = Calendar.current let date1 = calendar.date(from: DateComponents(year: 2017))! let date2 = calendar.date(from: DateComponents(year: 2018))! let date3 = calendar.date(from: DateComponents(year: 2019))! var dates = [date1, date2, date3] print(dates) // [2016-12-31 15:00:00 +0000, 2017-12-31 15:00:00 +0000, 2018-12-31 15:00:00 +0000]
これまで(Swift2以前)
orderedAscending
とorderedDescending
とで、
一見、どちらがa > b
で、どちらがa < b
なのかかがわかりづらい。
dates.sort { (d1, d2) -> Bool in return d1.compare(d2) == .orderedDescending } print(dates) // [2018-12-31 15:00:00 +0000, 2017-12-31 15:00:00 +0000, 2016-12-31 15:00:00 +0000]
Swift3以降
比較演算子が扱えることによって直感的でわかりやすくなった。
dates.sort { (d1, d2) -> Bool in return d1 > d2 } print(dates) // [2018-12-31 15:00:00 +0000, 2017-12-31 15:00:00 +0000, 2016-12-31 15:00:00 +0000]