Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

swift - How do you cast a UInt64 to an Int64?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...