Mastering macOS Programming
上QQ阅读APP看书,第一时间看更新

Variables and types

We can declare variables as follows:

var a: Int = 1

In the preceding line of code, a is declared to be of type Int, with a value of 1. Since only an Int can be assigned the value 1, Swift can automatically infer the type of a, and it is not necessary to explicitly include the type information in the variable declaration:

var a = 1

In the preceding code, it is equally clear to both Swift and the reader what type a belongs to.

What, no semicolons?
You can add them if you want to, and you'll have to if you want to put two statements on the same line (why would you do that?). But no, semicolons belong to C and its descendants, and despite its many similarities to that particular family of languages, Swift has left the nest.

The value of a var can be changed by simply assigning to it a new value:

var a = 1 
a = 2

However, in Swift, we can also declare a constant, which is immutable, using the let keyword:

let b = 2 

The value of b is now set permanently. The following attempt to change it will produce a compiler error:

b = 3 

The error is shown in the following screenshot:

As can be seen here, Xcode also suggests how to fix it, by offering to change the let declaration to a var.

If you do not need to change a variable, use let. Indeed, if you never change the value of a var once you have declared it, Xcode will suggest that you change it to let:

The let keyword is a little different to using the const keyword in C (or its equivalent in many other languages), because the value of the declaration is evaluated at runtime, not compile time, enabling it to be set dynamically, according to values not available at compile time.