Last active
August 29, 2015 14:07
-
-
Save pyrtsa/ae251cd74cd6d095a2b1 to your computer and use it in GitHub Desktop.
An example of dealing with NSDate in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
// MARK: Comparable instance for NSDate | |
public func <(a: NSDate, b: NSDate) -> Bool { | |
return a.compare(b) == .OrderedAscending | |
} | |
public func ==(a: NSDate, b: NSDate) -> Bool { | |
return a.compare(b) == .OrderedSame | |
} | |
extension NSDate : Comparable {} | |
// MARK: Examples: | |
let now = NSDate() | |
let tomorrow = now.dateByAddingTimeInterval(24 * 3600) | |
let yesteday = now.dateByAddingTimeInterval(-24 * 3600) | |
let minuteAgo = now.dateByAddingTimeInterval(-60) | |
let dates: [NSDate] = [now, tomorrow, yesteday, minuteAgo] | |
sorted(dates) | |
minElement(dates) // Watch out here: minElement crashes for empty arrays! | |
maxElement(dates) // ...maxElement likewise! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment