我需要从DispatchTimeInterval
(或Double
)中减去NSTimeInterval
。
是否有将DispatchTimeInterval
转换为NSTimeInterval
的标准方式?
答案 0 :(得分:4)
DispatchTimeInterval
是一个枚举:
public enum DispatchTimeInterval : Equatable {
case seconds(Int)
case milliseconds(Int)
case microseconds(Int)
case nanoseconds(Int)
case never
}
您可以使用
初始化DispatchTimeInterval
let tenSeconds: DispatchTimeInterval = .seconds(10)
let tenNanoseconds: DispatchTimeInterval = .nanoseconds(10)
要从枚举中获取值,您需要将值与枚举中的案例值匹配
if case .seconds(let value) = tenSeconds {
print("DispatchTimeInterval is seconds \(value)")
} else if case .nanoseconds(let value) = tenNanoseconds {
print("DispatchTimeInterval is seconds \(value)")
}
转换功能可能如下所示:
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
更新:
创建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
}
}
答案 1 :(得分:0)
一个快速的解决方案是创建一个TimeInterval
扩展名,并在其中添加一个带有failable initializer参数的DispatchTimeInterval
。以下Swift 5代码展示了如何实现它:
import Foundation
extension TimeInterval {
init?(dispatchTimeInterval: DispatchTimeInterval) {
switch dispatchTimeInterval {
case .seconds(let value):
self = Double(value)
case .milliseconds(let value):
self = Double(value) / 1_000
case .microseconds(let value):
self = Double(value) / 1_000_000
case .nanoseconds(let value):
self = Double(value) / 1_000_000_000
case .never:
return nil
}
}
}
用法:
let dispatchTimeInterval = DispatchTimeInterval.seconds(5)
let timeInterval = TimeInterval(dispatchTimeInterval: dispatchTimeInterval)
print(String(describing: timeInterval)) // Optional(5.0)
let dispatchTimeInterval = DispatchTimeInterval.milliseconds(30)
let timeInterval = TimeInterval(dispatchTimeInterval: dispatchTimeInterval)
print(String(describing: timeInterval)) // Optional(0.03)