Swift Basics

Love it? Share it!


Swift is one of the fastest growing programming language created by Apple in 2014. Swift makes it easy to write fast and safe programs.

If you want to learn the basics of Swift, you’ve come to the right place. I’ve created this course as a series of short articles and each bite-sized part will teach you a specific feature in just a few seconds.

What is programming

Programming is giving a set of instructions to a computer to execute. It’s like providing a recipe to cook something. Computer simply follows the instructions and the more complex they are, the more complex the result.

Programming plays a key role in how we participate in politics, how we buy things, and how we stay in touch with one another. While learning to program may initially be frustrating, if you choose to stick with it, you’ll be able to make some brilliant things.

Swift and Xcode

To start, you’ll need Xcode installed on your Mac. Xcode is available for free from the Mac App Store. Once it’s installed on your Mac, run it and choose File -> New -> Playground…

Or you can use the ⌥⇧⌘N shortcut.

Playground is a sandbox where you can write your code on the left and get immediate results on the right.

Keep the default settings (Blank playground for iOS) and hit the Next button. You can name your playground and save it to the location of your choice.

You should see your playground and first, you want to click that top left icon to hide the directory structure so it won’t distract you for now.

Alright! You’re all set and we can start learning Swift.


Your playground has three lines of code now. You can ignore the first two for now, but focus on the third line where you can see the declaration of a variable.

A variable is like a storage where you keep some values. This storage is called a variable because its content can  vary which means that you can reuse or change it. You’re probably familiar with the word variability.

A variable is a way of saving a value (a piece of information) with a specific name. By naming a value, we can later recall and reuse that value again in our code. We can also easily change that value throughout our code.

With variables we can start using a very important programming concept: repetition. This means that instead of writing out the same piece of information every time we need it, we store it in a variable, our computer remembers it and can repeat it back.

Our code creates such a variable:

var str = "Hello, playground"

This new variable is called  str and its value is “Hello, playground”.

Now, click the tiny arrow below the code to execute it:

On the right of the playground you’ll see “Hello, playground” in the output area. This is how you know that the value has been set for our variable:

And because the str is a variable we can change it:

str = "Have a nice day"

Notice that this time, we don’t use the  var keyword. That because the str has already been created and we are just changing its value now:


In the previous chapter, you learned that a variable has a content that can be changed. Sometimes, this makes a perfect sense. For example, your age changes every year, so it makes sense to create a variable ageand change its content each time you have a birthday.

On the other hand, your birth date should never change as it’s constantlythe same. That’s why Swift lets you create constants, assign them an initial value, which can’t be changed later, ever.

Let’s test this. In your playground, create a new variable called age and assign it your current age:

var age = 40

Below, create a new constant called birthdate and assign it the date your were born:

let  birthdate = "27.08.1981"

Now, the important part. Let’s say, you’ll return to this code one year later. To change your age, you just assign a new value to the age variable:

age = 41

However, your birth date can never change, so this code won’t work:

birthdate = "01.01.2021"

As you can see in your playground, the complier shows the error:

…and even offers a solution:

However, we don’t want to make this fix, because the date you were born should stay constant, so we rather don’t attempt to change it.

Data types

Data is a piece of information, it’s the basic unit in programming the we use to build programs. Without it, we couldn’t write any programs.

Data types (or just types) are different types of data that indicates characteristics of data so the computer can perform the appropriate operation.

In short, they tell us how data can be stored and what types of operations we can perform. For example, we can write a program that squares numbers, but it wouldn’t be able to square a word.

The most basic data types are called primitives. They are so basic that you can find them in pretty much every programming language. They include:

  • Numbers
  • Strings
  • Boolean values (True or False)

Every variable in Swift must be of a specific data type. That’s because Swift is a type-safe language. You set the type when you declare a variable and you must keep the same type if you change the value of that variable later.

Type inferring

So far, we didn’t specify the data type for our variables because we relied on the type inferring feature of Swift. This means that Swift can recognize automaticaly the data type of the most common values and set the corrent data type for us when we declare the variable.

Remember how we declared str = "Have a nice day" ?

The value "Have a nice day" we assigned to the str variable is of type String and it’s very easy for Swift to recognize it, because it’s enclosed in double quotes.

Without type inferring, we would have to specify the data type like this:

str: String = "Have a nice day"

Go ahead and write this code to the bottom of your playground (delete the line where you attempted to change the value of the birthdate constant first):

var name: String = "Jan"

This is how your code should look like now:

Similarly, you could specify the type of Integer for your age variable like this:

var age: Int = 40

Int stands for Integer and it means a simple number. Go ahead and modify your code so it includes the specification of Integer type:

Strings and integers

Sometimes, it feels like programmers want to sound sophisticated and instead of saying “text” and “number”, they say “string” and “integer”, but it’s more complicated.

These are two of the most common types of values you can store to constants or variables as you already know. But once you initialy store a specific type of value to a variable, you can’t change that data type later.

You can change the value, but the new value must be of the same type. For example, you can change one String value to another one, but you can’t change String to Integer.

Let’s test this in our playground.

When I try to change my age to “42”, Xcode will protest, because I try to store String (quotes are used for text so even though 42 is a number, it’s treated as a text) to the variable that holds only Integers. It’s like trying to fit rectangle into a circle.

In case you wonder, Strings consist of characters strung together, like beads in a necklace, hence the name.

Ok, delete the last line of code and remember that you must respect the type you used when you created your variable.

String interpolation

In Swift, you can place any type of variable right inside your string, you just need to write a backslash,  \, followed by a variable name in parentheses. This feature is called string interpolation.

For example:

var score = 50
var str = "Your score is \(score)"

The output of the  str variable will be “Your score is 50”.


Double is short name for “double-precision floating-point number”, and it’s a fancy way of saying that it holds fractional values such as 24.5, or 3.141592654.

Whenever you create a variable with a fractional number, Swift automatically gives that variable the data type  Double. For example:

var pi = 3.141

Of course, you can specify the data type manually if you like:

var pi: Double = 3.141

Doubles are different from integers, and you can’t mix them by accident, if you try it, you’ll get an error:

var pi: Int = 3.141

Ok, delete the last line before we move on.


Booleans or Boolean values represent the logical ideas of true and false.

Booleans only have two values:  true and  false. The term boolean is based on the name of the inventor of logic, George Boole.

We use booleans to determine the validity and to make decisions. You can think of booleans in a myriad of ways, like on and off, yes and no, sometimes even 1 and 0.

It’s important to remember that the words  true and  false we use to represent boolean values are different from the strings  “true” and “false”.


Operators are special symbols that represent an  operations performed on data *, such as addition perfomed with the plus sign (+). Operations enable us to *transform our data into something else.

In programming, there are three main types of operators:

  • arithmetic operators for making calculations,
  • comparison operators for comparing data,
  • logical (Boolean) operators for creating logical expressions.

Arithmetic operators

The original purpose of computers was to perform long calculations for us because they are quite tedious and time consuming when performing on a paper.

To perform calculations, we use arithmetic operators like addition (+), subtraction (-), multiplication (*), and division (/).

  • Addition adds a specific amount to a number like  1 + 2 = 3
  • Subtraction takes away a specific amount from a number like  3 - 2 = 1
  • Multiplication takes a number and repeats it a specified number of times like  2 * 3 = 6
  • Division takes a number and divides it by another number:  6 / 3 = 2

Let’s say you want to store 5 apples in the apples variable. Next, you want to multiply them by two and store the result in a new variable called myApples and finally, you want to subtract 6 apples and store the final result in the finalCount variable:

var apples = 5  
var myApples = apples * 2  
var finalCount = myApples - 6

Write this code in playground and check out the value of the finalCount variable. It should be equal to 4.

Comparison operators

Comparison operators allows us to check if a value is correct or to compare values and evaluate their relationship.

They don’t evaluate to a number, but to boolean values  true or  false. That’s why they are also known as  boolean expressions.

Comparison operators include:

  • Less than  < — value to the left is  less than the value to the right:  2 < 10
  • Greater than  > — value to the left is  more than the value to the right:  10 > 5
  • Equals  == — value to the left is  equal to the value to the right:  3 == 3

Notice how we use a double-equal sign ( == ) to compare values instead of a single-equal sign ( = ) you might know from the math class.

That’s because a single-equal sign ( = ) is used in programming to set a value of something, like you would do with a variable, not to compare two values.

There’s also the identity operator in Swift ( === ) which checks if two instances of a class point to the same place in memory.

Logical operators

Unlike comparison operators that compare just two values, logical operators allow us to deal with more than two values as they can evaluate multiple boolean expressions.

Logical operators look at several relationships by determining the validity of the overall expression.

Logical operators include:

  • AND  ((2 > 1) AND (3 < 4)) is the same as  (TRUE AND TRUE). Both expressions evaluate to true, so the final result is also true.
  • OR  ((10 > 5) OR (2 > 10)) is the same as  (TRUE OR FALSE). One of the expressions evalutes to true, so the final result is true.
  • NOT  NOT (1 < 3) evaluates to  NOT (TRUE). The expression always evaluates to the opposite value.


Love it? Share it!
Jan Zavrel
Jan Zavrel

Jan Zavrel is an author, teacher, online entrepreneur and Evernote Certified Consultant who runs multiple projects focused on productivity, fitness, web development and passive income. He is also active as an instructor on Udemy and Skillshare. His books are available via Amazon.