An Introduction to Swift
Clear examples to demonstrate the basics.
Topics Covered
- Variables
- Data Types
- Optional Values
- Collections
- For-In Loops
- Functions
Variables — Var vs Let
Declaring a variable in swift is easy.
var name = "Wallace"
Here we are assigning the value of “Wallace”
to a variable called name
.
Using var
informs us that the variable is mutable. A mutable variable is one that can have its value changed after creation.
name = "Gromit"
The variable name
now only holds a reference to the value "Gromit"
. The reference to "Wallace"
has been lost.
Like many programming languages, Swift supports the notion of immutability. To declare an immutable variable, we use the keyword let
.
let neverChange = true
Let’s see what happens if we try to change its value.
Xcode gives us a clear error, informing of our invalid assignment.
You should use let
when you are certain that the variable does not need to be changed in the future. Doing this will…