I need to subtract a DispatchTimeInterval
from an NSTimeInterval
(or Double
).
Is there a standard way to convert a DispatchTimeInterval
to an NSTimeInterval
?
DispatchTimeInterval
is a enum:
public enum DispatchTimeInterval : Equatable {
case seconds(Int)
case milliseconds(Int)
case microseconds(Int)
case nanoseconds(Int)
case never
}
You can initialize DispatchTimeInterval
using:
let tenSeconds: DispatchTimeInterval = .seconds(10)
let tenNanoseconds: DispatchTimeInterval = .nanoseconds(10)
To get values from enum you need to match value with a case values in enum
if case .seconds(let value) = tenSeconds {
print("DispatchTimeInterval is seconds \(value)")
} else if case .nanoseconds(let value) = tenNanoseconds {
print("DispatchTimeInterval is seconds \(value)")
}
Converting function might be look following:
func toDouble(_ interval: DispatchTimeInterval) -> Double? {
var result: Double? = 0
switch interval {
case .seconds(let value):
result = Double(value)
case .milliseconds(let value):
result = Double(value)*0.001
case .microseconds(let value):
result = Double(value)*0.000001
case .nanoseconds(let value):
result = Double(value)*0.000000001
case .never:
result = nil
}
return result
}
More about Enumeration see in Apple Documentation
UPDATE:
Create extension to DispatchTimeInterval
extension DispatchTimeInterval {
func toDouble() -> Double? {
var result: Double? = 0
switch self {
case .seconds(let value):
result = Double(value)
case .milliseconds(let value):
result = Double(value)*0.001
case .microseconds(let value):
result = Double(value)*0.000001
case .nanoseconds(let value):
result = Double(value)*0.000000001
case .never:
result = nil
}
return result
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With