An Introduction to Swift

Giuseppe
The Dev Café
Published in
6 min readJun 12, 2020

--

Clear examples to demonstrate the basics.

Photo by Author

Topics Covered

  1. Variables
  2. Data Types
  3. Optional Values
  4. Collections
  5. For-In Loops
  6. 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…

--

--