Last active
October 16, 2019 04:32
-
-
Save IanKeen/2db3cc757307fb49e358 to your computer and use it in GitHub Desktop.
Working Swiftly with NSTimeInterval
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
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 } | |
} | |
} |
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
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