Why does the Swift language guide suggest using Int “even when values are known to be non-negative”?

I don’t think using UInt is as safe as you think it is. As you noted:

let age:UInt = -3

results in a compiler error. I also tried:

let myAge:Int = 1
let age:UInt = UInt(myAge) - 3

which also resulted in a compiler error. However the following (in my opinion much more common in real programs) scenarios had no compiler error, but actually resulted in runtime errors of EXC_BAD_INSTRUCTION:

func sub10(num: Int) -> UInt {
    return UInt(num - 10) //Runtime error when num < 10
}
sub10(4)

as well as:

class A {
    var aboveZero:UInt
    init() { aboveZero = 1 }
}
let a = A()
a.aboveZero = a.aboveZero - 10 //Runtime error

Had these been plain Ints, instead of crashing, you could add code to check your conditions:

if a.aboveZero > 0 {
    //Do your thing
} else {
    //Handle bad data
}

I might even go so far as to equate their advice against using UInts to their advice against using implicitly unwrapped optionals: Don’t do it unless you are certain you won’t get any negatives, because otherwise you’ll get runtime errors (except in the simplest of cases).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)