Swift is Apple’s new programming language for developing applications for iOS, watchOS, tvOS and Mac OS. In this Swift tutorial you will learn all its basics.

What will you learn in this “Swift Tutorial For Beginners”?

This Swift tutorial includes the following topics:

Downloading Xcode

Playgrounds

“Hello World!” program

Variables

Constants

Type Annotations

Conditionals

Loops

Optionals

Functions

There will be more parts in this “Swift Tutorial For Beginners” series.

Downloading Xcode

The first step in becoming a Swift guru is downloading Xcode. You can install it directly from the App Store. Xcode is Apple’s IDE for developing for all of the Apple platforms: iOS, watchOS, tvOS and Mac OS.

Playgrounds

Most of the times you will work in a project. But Xcode has one very interesting feature that is a huge help for both beginners and experts: Playgrounds. They allow you to write Swift code that gets directly executed. So if you want to learn something or if you want to experiment a little bit, you can just open a playground and do it without compiling and executing a huge project.

If you are working on a project, it is very advisable to always have a playground open. This way you can quickly perform some small experiments. Also for this Swift tutorial you should practice everything in a playground.

Ok, let’s start and open Xcode. Then click on “Get started with a playground” in the welcome window. If you don’t see that window, click on File -> New -> Playground. Afterwards, you have to specify the name and the location of the playground and we can start.

Hello World!

In most of the programming books the very first program is one that simply prints “Hello World!” And we don’t want do break with good old traditions, do we?

So take your playground and enter the following line:

print("Hello World!") 1 print ( "Hello World!" )

On the right side of the playground you can see now the output.

Congratulations, you have just programmed your very first Swift program!

Variables

After printing the first sentence, we want to do some real programming. For that you need variables. Variables enables you to store a value like a number or a string in a placeholder. For that, we use the keyword var:

var aNumber = 5 1 var aNumber = 5

Now we have a variable called aNumber that has a value of 5. What can we do now with it? Well, first of all we can change the value:

aNumber = 10 1 aNumber = 10

We can even assign a mathematical term and the result gets stored in that value:

aNumber = 5 + 6 1 aNumber = 5 + 6

It is also possible to print the value of a variable. For that you need to put the value in a special term:

print("The number is equal \(aNumber)") 1 print ( "The number is equal \ ( aNumber ) " )

Variables can be of different types. So you can also assign for example a string, floating point number or a bool (true or false):

var aString = "A String" var aDoble = 13.3 var aBool = true 1 2 3 var aString = "A String" var aDoble = 13 . 3 var aBool = true

However, after you have assigned one value, you can only assign the same type:

aBool = "A String" //Compiler Error 1 aBool = "A String" //Compiler Error

The compiler is a program that translates your code into machine code. If you are doing something that the compiler doesn’t understand or is against the rules, there will be an error.

Constants

As the name says, a variable can be changed. But there are also constants, that cannot be changed after their first declaration. For that you have to use the keyword let:

let aConstantNumber = 10 1 let aConstantNumber = 10

If you now try to change the constant, there will be an error:

aConstantNumber = 10 // Compiler Error 1 aConstantNumber = 10 // Compiler Error

So why should you even use a constant? Well, sometimes you don’t want that a value gets changed accidentally after its first declaration. For example, if you assign the name of a person, the value should not be changed again.

Type Annotations

As we have learned already, variables gets a type after the first declaration. But it is also possible to specify the type directly:

let aNumber: Int = 10 1 let aNumber : Int = 10

The result is the same as in the previous example, but now the code is easier to read. It is very clear at the first sight that the variable has the type Int. Of course there are more types:

var aString: String = "A String" var aDouble: Double = 13.3 var aBool: Bool = true 1 2 3 var aString : String = "A String" var aDouble : Double = 13 . 3 var aBool : Bool = true

Conditionals

A program that does always the same is very boring. For this reason there are so called conditionals that control the program flow. For example, you want to have different outputs depending on the result of a calculation. The most common conditional is the so called if condition. Let’s take a look at an example:

var number1 = 5 var number2 = 10 if number1 < number2 { print("number1 is smaller than number2") } 1 2 3 4 5 6 var number1 = 5 var number2 = 10 if number1 < number2 { print ( "number1 is smaller than number2" ) }

In this example, we check after the keyword if whether number1 is smaller than number2 or not. If that is the case, the code inside of the curly brackets – the so-called if block – gets executed. You can put as much code inside that block as you want.

Additionally you can define a behaviour if the if conditions does not hold true:

var number1 = 5 var number2 = 10 if number1 < number2 { print("number1 is smaller than number2") } else { print("number1 is not smaller than number2") } 1 2 3 4 5 6 7 8 var number1 = 5 var number2 = 10 if number1 < number2 { print ( "number1 is smaller than number2" ) } else { print ( "number1 is not smaller than number2" ) }

And you can even have several if cases:

if number1 < number2 { print("number1 is smaller than number2") } else if number2 < number1 { print("number2 is than number2") } else { print("number1 is equal number2") } 1 2 3 4 5 6 7 if number1 < number2 { print ( "number1 is smaller than number2" ) } else if number2 < number1 { print ( "number2 is than number2" ) } else { print ( "number1 is equal number2" ) }

The second conditional statement in Swift is the switch – conditional. It takes one value and compares it against several possible matching patterns. Let’s look directly at an example:

switch name { case "Mick": print("The name is Mick") case "John": print("The name is John") default: print("The name is neither Mick nor John") } 1 2 3 4 5 6 7 8 switch name { case "Mick" : print ( "The name is Mick" ) case "John" : print ( "The name is John" ) default : print ( "The name is neither Mick nor John" ) }

The value that gets investigated is name. It is written directly after the switch keyword. Then, after every case one possible value it specified. If name matches that value, the following code gets executed. If not, the next case is checked. If none of the possibilities matches, the code after default gets executed. You have much more possibilities with a switch conditional, but for the beginning this is enough to know.

Loops

Besides the conditionals there is one more very important feature to control the program flow: Loops. With loops you can execute a block of code several times. Swift has 3 three types of loops: while-loop, repeat-while-loop and for-loop.

While-Loop

Let’s take a look at the while-loop:

var i = 0 while (i < 10) { print("Hello World") i = i + 1 } 1 2 3 4 5 6 var i = 0 while ( i < 10 ) { print ( "Hello World" ) i = i + 1 }

After the keyword while, a condition is specified. As long as this condition holds true, the block of code after that line is executed repeatedly. So in this case ten times. If you wouldn’t change the value of i, the loop would never stop.

Repeat-While-Loop

The repeat-while-loop is very similar to the while-loop. However, the condition is not specified before the block of code that gets executed, but afterwards:

var i = 10 repeat { print("Hello World") i = i + 1 } while (i < 10) 1 2 3 4 5 6 var i = 10 repeat { print ( "Hello World" ) i = i + 1 } while ( i < 10 )

So what’s the point in using a repeat-while-loop instead of using a while-loop? The main difference is, that the code inside the loop gets executed at least once in a repeat-while-loop:

var i = 11 repeat { print("Hello World") i = i + 1 } while (i < 10) 1 2 3 4 5 6 var i = 11 repeat { print ( "Hello World" ) i = i + 1 } while ( i < 10 )

Although the condition holds never true, “Hello World” is printed at least once. Sometimes you want this behaviour, and sometimes you don’t. So it depends on the use case.

For-Loop

For-loops are very handy. The for-loop performs a set of statements for each item in a sequence. There are several ways how you can specify this sequence. Let’s take a look at an example:

for i in 1...10 { print("This iteration number \(i)") } 1 2 3 for i in 1 ... 10 { print ( "This iteration number \ ( i ) " ) }

If you are using three dots, the last number – in this case 10 – is included. Alternatively, you can use the following syntax:

for i in 1..<10 { print("This iteration number \(i)") } 1 2 3 for i in 1 .. < 10 { print ( "This iteration number \ ( i ) " ) }

This time, 10 is not included. There is another way how you can write a for loop. You can call it a “traditional C-style for-loop”:

for var i = 1; i <= 10; i++ { print("This iteration number \(i)") } 1 2 3 for var i = 1 ; i <= 10 ; i ++ { print ( "This iteration number \ ( i ) " ) }

Again, the code gets executed 10 times. You specify three parts that are separated by semicolons: First, a variable is initialised with a start value. Then you specify a condition that is checked right before every iteration of the loop. If it holds true, the block afterwards gets executed. And last, you specify a term that gets executed right after every iteration of the loop. In this case, the variable i gets increased by 1. The term i++ is basically the same as i = i + 1.

Optionals

Optionals are a very special feature of Swift and it is very important to learn about this right from the start. Imagine that you have a variable, but sometimes it doesn’t make sense for the variable to have a value. This could happen for example, if you have a variable that stores the middle name of a person. What is, if the person doesn’t have a middle name? Then we could of course assign just an empty name:

var middleName: String = "" 1 var middleName : String = ""

However, if we make middleName to an optional we can assign nil which means “no value at all”. For a variable to become an optional you have to declare it. For that you use the question mark after the type annotion:

var middleName: String? = nil 1 var middleName : String ? = nil

An optional is still allowed to have a non-nil value.

You can’t access an optional like a normal variable, though. If you do this, there will be compiler error:

var anotherName: String = middleName //Compiler Error 1 var anotherName : String = middleName //Compiler Error

For that you need to unwrap the optional. There are several ways to do this. First, you could use an exclamation mark:

var anotherName: String = middleName! 1 var anotherName : String = middleName !

However, you are only allowed to unwrap an optional this way, if it doesn’t have the value nil. Otherwise there will be an error at execution time.

So it is better to check whether the optional is nil or not, right? We can do so by using the so-called optional binding:

var middleName: String? = "John" var anotherName: String = "Michael" if let name = middleName { anotherName = name } 1 2 3 4 5 6 var middleName : String ? = "John" var anotherName : String = "Michael" if let name = middleName { anotherName = name }

This might look a little bite strange at first, but it is in fact very easy: If middleName is equal to nil,nothing happens at all and the block inside the if condition will not be executed.

However, if middleName is not nil, then name gets the value and the if blog gets executed. Inside the block, name is NOT an optional anymore, so it behaves like a normal constant.

Functions

You often encounter the situation where some code can be applied to a l0t of different situation. If this is the case, you can put this code inside a function that can be called from other code positions. Let’s start by building a simple function that just prints “Hello World”:

func printHelloWorld() { print("Hello World!") } 1 2 3 func printHelloWorld ( ) { print ( "Hello World!" ) }

In fact, if you enter this code snippet into a playground, you don’t see any output on the right side at all. This changes, if you are calling the function:

func printHelloWorld() { print("Hello World!") } printHelloWorld() 1 2 3 4 5 func printHelloWorld ( ) { print ( "Hello World!" ) } printHelloWorld ( )

If you are calling the function a second time, you see that on the right side of the playground there is the text “(2 times)”:

func printHelloWorld() { print("Hello World!") } printHelloWorld() printHelloWorld() 1 2 3 4 5 6 func printHelloWorld ( ) { print ( "Hello World!" ) } printHelloWorld ( ) printHelloWorld ( )

You can deliver a function additional informations, so-called arguments. Every argument needs a name and a type. Then, you can access this variable inside the function:

func printANumber(number:Int) { print("The number is \(number)") } 1 2 3 func printANumber ( number : Int ) { print ( "The number is \ ( number ) " ) }

Now you can call the function with a parameter:

func printANumber(number:Int) { print("The number is \(number)") } printANumber(5) 1 2 3 4 5 func printANumber ( number : Int ) { print ( "The number is \ ( number ) " ) } printANumber ( 5 )

In this case, the output is “The number is 5”.

You can even specify more than one argument. Then, you need to specify all the names of the arguments except the first one, if you are calling the function:

func printNumbers(number1:Int, number2:Int, number3:Int) { print("The number are \(number1), \(number2), \(number3)") } printNumbers(5, number2:10, number3:15) 1 2 3 4 5 func printNumbers ( number1 : Int , number2 : Int , number3 : Int ) { print ( "The number are \ ( number1 ) , \ ( number2 ) , \ ( number3 ) " ) } printNumbers ( 5 , number2 : 10 , number3 : 15 )

The last important functionally of a function is, that it is able to return a value. For that you need to specify the type of the value that gets returned. You do this right after the arguments. In the function itself the value must be returned by the keyword return.

Let’s take a look at an example: Imagine you want to write a function that takes two numbers as an argument and returns the bigger one of them. This looks like this:

func maxOfNumbers(number1: Int, number2: Int) -> Int { if number1 < number2 { return number2 } else { return number1 } } maxOfNumbers(5, number2: 10) 1 2 3 4 5 6 7 8 9 func maxOfNumbers ( number1 : Int , number2 : Int ) -> Int { if number1 < number2 { return number2 } else { return number1 } } maxOfNumbers ( 5 , number2 : 10 )

As exspected, the output is 10.

Where to go from here?

That was Part 1 of the Swift Tutorial. Now you are familiar with the most basic language features of Swift. It is a very good basis to learn more. First of all, you should experiment on your own to get more comfortable with Swift. Furthermore, you can check out some posts on this blog that deal with the topics of this tutorial:

In the next part (not published yet) of the “Swift Tutorial For Beginners” series we will discuss more advanced stuff of Swift. Stay tuned!

References

Image: @ Andrey_Popov / shutterstock.com

The Swift Programming Language