NSDate operators
1 min read
I personally find this a bit of a mouthful, especially if you have to type it a lot:
if someDate.compare(otherDate) == .OrderedAscending {
// Do stuff
}Update, Oct 10, 2017: These are now built-in for Date. Leaving these here like they are (Swift 2), since the whole post is just about them.
But we can have a few operators to make our lives a bit easier:
func <(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.compare(rhs) == .OrderedAscending
}
func <=(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs < rhs || lhs == rhs
}
func >(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.compare(rhs) == .OrderedDescending
}
func >=(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs > rhs || lhs == rhs
}
func ==(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.compare(rhs) == .OrderedSame
}
func !=(lhs: NSDate, rhs: NSDate) -> Bool {
return !(lhs == rhs)
}I think this is not only prettier and shorter, but a bit more expressive, as well:
if someDate < otherDate {
// Do stuff
}