A Quick Note on Type Inference

Take a look at this code that you entered earlier:

for i in 1...5 {
    ++myFirstInt
    print("myFirstInt equals \(myFirstInt) at iteration \(i)")
}

Notice that i is not declared to be of the Int type. It could be, as in: for i: Int in 1...5 (the let portion of the declaration is assumed by the syntax for you). But it is not necessary. The type of i is inferred from its context. In this example, i is inferred to be of type Int because the specified range contains integers.

Type inference is handy. It lets you type less, which makes for fewer typos. However, there are a few cases where you need to specifically declare the type. We will highlight those when they come up. In general, however, we recommend ...

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.