alex alex - 3 years ago 79
Swift Question

get `(UInt8.min + UInt8.max) * 3` to console

With swift, when I input this code below, I could not get the sumInt number to console?

let minValue=UInt8.min
let maxValue=UInt8.max
let sumInt=(maxValue+minValue)*3
println(sumInt)


after I change the code as below

let minValue=UInt8.min
let maxValue=UInt8.max
let sumInt:Int=(maxValue+minValue)*3
println(sumInt)


I got an error


Could not find an overload for '*' that accepts the supplied arguments


how can I make it right?

Answer Source

Its because the type you get from the sum is again a UInt8.. try

 let minValue=UInt8.min
    let maxValue=UInt8.max
    let sumInt:Int8=(maxValue+minValue)*3 //overflow
    println(sumInt)

Or

let minValue=UInt8.min
let maxValue=UInt8.max
let sumInt:Int=(Int)(maxValue+minValue)*3
println(sumInt)

But notice that the number sumInt will now be valid because its no longer a UInt8 which goes up to only 255 and it overflows in the first code snippet.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download