What does "Array indices are checked for out-of-bounds errors" from the Swift book mean?

Are checked by who? To me, it sounds like they are automatically checked, but as far as I know, this is not the case.

They are checked automatically. It means if you write this:

let array = [0, 1, 2, 3, 4, 5]
let elementFromIt = array[1000]

Swift will notice that 1000 is out of bounds and will crash your program before any harm can be done.

In some other languages, it instead would have succeeded and read arbitrary data from whatever happens to be stored in memory at the position 905 past the end of the array. The ability to read like that is already a security vulnerability, but the ability to write to such an index leads to direct corruption of that far‐flug part of the program. All sorts of madness would start to happen that you could never foresee. Swift deems immediately crashing to be the better philosophy.

6 Likes

Oh, I see, but that's available in Objective-C too, right?

NSArray does bounds checking, yes. But C arrays—which are also available from Objective C—do not.

4 Likes

And what about "Integers are checked for overflow"?

let x = Int.max // 9223372036854775807

// The basic operation is checked:
let y = x + 1 // Crash.
// Cannot represent the number. (Not enough bits available.)

// An unchecked variant can be used instead (by adding “&”):
let z = x &+ 1 // −9223372036854775808
// It has wrapped around to the lowest number.
// (Kind of like continuing west past 180° W
//  and winding up at 179° E.)
4 Likes

Thank you a lot!

1 Like
Terms of Service

Privacy Policy

Cookie Policy