我曾经在Objective-C中使用以下内容:
double currentTime = CFAbsoluteTimeGetCurrent();
// self.startTime is called before, like
// self.startTime = CFAbsoluteTimeGetCurrent();
double elapsedTime = currentTime - self.startTime;
// Convert the double to milliseconds
unsigned long long milliSecs = (unsigned long long)(elapsedTime * 1000);
我现在的快捷代码:
let currentTime: Double = CFAbsoluteTimeGetCurrent()
let elapsedTime: Double = currentTime - startTime
let milliSecs: CUnsignedLongLong = elapsedTime * 1000
但是我收到的错误是double
无法转换为有意义的CUnsignedLongLong
。有没有办法像Objective-C一样投射它?有办法解决这个问题吗?
答案 0 :(得分:21)
有没有办法像在Objective C中那样投射它?有办法解决这个问题吗?
let milliSecs = CUnsignedLongLong(elapsedTime * 1000)
或者
let milliSecs = UInt64(elapsedTime * 1000)
答案 1 :(得分:4)
CUnsignedLongLong
在标准库中通过以下方式定义:
typealias CUnsignedLongLong = UInt64
因此,要将Double
转换为CUnsignedLongLong
,您需要使用
CUnsignedLongLong
的新实例
CUnsignedLongLong(elapsedTime * 1000)
或
UInt64(elapsedTime * 1000)
答案 2 :(得分:2)
Swift不允许隐式类型转换。使用构造函数为其类型创建值。
let milliSecs = CFUnsignedLongLong(elapsedTime * 1000)