Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you cast a UInt64 to an Int64?

Tags:

swift

Trying to call dispatch_time in Swift is doing my head in, here's why:

 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC), dispatch_get_main_queue(), {
            doSomething()
            })

Results in the error: "Could not find an overload for '*' that accepts the supplied arguments".

NSEC_PER_SEC is an UInt64 so time for some experiments:

let x:UInt64 = 1000
let m:Int64 = 10 * x

Results in the same error as above

let x:UInt64 = 1000
let m:Int64 = 10 * (Int64) x

Results in "Consecutive statements on a line must be separated by ';'"

let x:UInt64 = 1000
let m:Int64 = 10 * ((Int64) x)

Results in "Expected ',' separator"

let x:UInt64 = 1000
let m:Int64 = (Int64)10 * (Int64) x

Results in "Consecutive statements on a line must be separated by ';'"

Etc. etc.

Damn you Swift compiler, I give up. How do I cast a UInt64 to Int64, and/or how do you use dispatch_time in swift?

like image 621
Gruntcakes Avatar asked Jul 02 '14 18:07

Gruntcakes


1 Answers

You can "cast" between different integer types by initializing a new integer with the type you want:

let uint:UInt64 = 1234
let int:Int64 = Int64(uint)

It's probably not an issue in your particular case, but it's worth noting that different integer types have different ranges, and you can end up with out of range crashes if you try to convert between integers of different types:

let bigUInt:UInt64 = UInt64(Int64.max) - 1      // 9,223,372,036,854,775,806
let bigInt:Int64 = Int64(bigUInt)               // no problem

let biggerUInt:UInt64 = UInt64(Int64.max) + 1   // 9,223,372,036,854,775,808
let biggerInt:Int64 = Int64(biggerUInt)         // crash!

Each integer type has .max and .min class properties that you can use for checking ranges:

if (biggerUInt <= UInt64(Int64.max)) {
    let biggerInt:Int64 = Int64(biggerUInt)     // safe!
}
like image 161
Nate Cook Avatar answered Oct 16 '22 09:10

Nate Cook