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.16 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!) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access