16

我曾经在 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

但是,我得到一个错误,即 adouble无法转换为 a CUnsignedLongLong,这是有道理的。有没有办法像在 Objective-C 中一样投射它?有没有解决的办法?

4

3 回答 3

27

有没有办法像在Objective C中一样投射它?有没有解决的办法?

let milliSecs = CUnsignedLongLong(elapsedTime * 1000)

或者

let milliSecs = UInt64(elapsedTime * 1000)
于 2015-07-27T17:33:37.403 回答
5

CUnsignedLongLong在标准库中定义为:

typealias CUnsignedLongLong = UInt64

因此,要将 a 转换DoubleCUnsignedLongLong,您需要创建一个CUnsignedLongLongusing的新实例

CUnsignedLongLong(elapsedTime * 1000)

或者

UInt64(elapsedTime * 1000)
于 2015-07-27T17:36:38.757 回答
2

Swift 不允许隐式类型转换。使用构造函数为其类型创建值。

let milliSecs = CFUnsignedLongLong(elapsedTime * 1000)
于 2015-07-27T17:41:09.600 回答