Skip to content

Instantly share code, notes, and snippets.

@pyrtsa
Last active August 29, 2015 14:07
Show Gist options
  • Save pyrtsa/ae251cd74cd6d095a2b1 to your computer and use it in GitHub Desktop.
Save pyrtsa/ae251cd74cd6d095a2b1 to your computer and use it in GitHub Desktop.
An example of dealing with NSDate in Swift
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