Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Last active October 16, 2019 04:32
Show Gist options
  • Save IanKeen/2db3cc757307fb49e358 to your computer and use it in GitHub Desktop.
Save IanKeen/2db3cc757307fb49e358 to your computer and use it in GitHub Desktop.
Working Swiftly with NSTimeInterval
enum TimePeriod {
case Seconds(Int)
case Minutes(Int)
case Hours(Int)
var timeInterval: NSTimeInterval {
switch self {
case .Seconds(let value): return NSTimeInterval(value)
case .Minutes(let value): return NSTimeInterval(value * 60)
case .Hours(let value): return NSTimeInterval(value * 60 * 60)
}
}
}
extension Int {
var seconds: TimePeriod { return .Seconds(self) }
var minutes: TimePeriod { return .Minutes(self) }
var hours: TimePeriod { return .Hours(self) }
}
extension NSTimeInterval {
init(periods: TimePeriod...) {
self = periods.reduce(0) { $0 + $1.timeInterval }
}
}
let time = NSTimeInterval(periods: .Hours(5), .Minutes(45))
//or using Int extension
let interval = NSTimeInterval(periods: 3.hours, 4.seconds)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment