17

I used to use the following in 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);

In my swift code I have at the moment:

let currentTime: Double = CFAbsoluteTimeGetCurrent()
let elapsedTime: Double = currentTime - startTime

let milliSecs: CUnsignedLongLong = elapsedTime * 1000

However I get the error that a double cannot be converted to a CUnsignedLongLong which makes sense. Is there a way to cast it like in Objective-C though? Is there a way around this?

GarethPrice
  • 1,072
  • 2
  • 14
  • 25

3 Answers3

27

Is there a way to cast it like in Objective C though? Is there a way around this?

let milliSecs = CUnsignedLongLong(elapsedTime * 1000)

Or

let milliSecs = UInt64(elapsedTime * 1000)
simons
  • 2,374
  • 2
  • 18
  • 20
6

CUnsignedLongLong is defined in the standard library by:

typealias CUnsignedLongLong = UInt64

So to convert a Double to CUnsignedLongLong, you need to create a new instance of CUnsignedLongLong using

CUnsignedLongLong(elapsedTime * 1000)

or

UInt64(elapsedTime * 1000)
David Skrundz
  • 13,067
  • 6
  • 42
  • 66
2

Swift doesn't allow for implicit type conversion. Create the value using the constructor for its type.

let milliSecs = CFUnsignedLongLong(elapsedTime * 1000)
orahman
  • 76
  • 3