Quick: Easy DispatchTime
Expressin' me some literals
November 10, 2016
Here's a quick bonus post. I find using DispatchTime
a bit less convenient than it should be. In a GUI application I almost always just want to specify a TimeInterval
, aka number of whole or fractional seconds.
Thankfully Swift extensions can grant my heart's desire:
extension DispatchTime: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) {
self = DispatchTime.now() + .seconds(value)
}
}
extension DispatchTime: ExpressibleByFloatLiteral {
public init(floatLiteral value: Double) {
self = DispatchTime.now() + .milliseconds(Int(value * 1000))
}
}
Now I can use async dispatch the way God intended:
DispatchQueue.main.asyncAfter(deadline: 5) { /* ... */ }
Russ Bishop
This blog represents my own personal opinion and is not endorsed by my employer.