Converting Between Integer Types

So far, all the operations you have seen have been between two values with exactly the same type. What happens if you try to operate on numbers with different types?

Listing 4.17  Adding values of different types

...
let a: Int16 = 200
let b: Int8 = 50
let c = a + b // Uh-oh!

This is a compile-time error. You cannot add a and b because they are not of the same type. Some languages will automatically convert types for you to perform operations like this. Swift does not. Instead, you have to manually convert types to get them to match.

In this case, you could either convert a to an Int8 or convert b to an Int16. Actually, though, only one of these will succeed. (Why? Reread the previous section!) ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.