Swift Tutorial

Swift Tutorial For Beginners: Part 1

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:

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

Screen Shot 2015-10-03 at 18.26.55

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:

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:

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

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

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

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

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:

If you now try to change the constant, there will be an 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:

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:

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:

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:

And you can even have several if cases:

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:

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:

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:

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:

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:

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

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”:

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:

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:

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:

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

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:

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”:

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:

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)”:

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:

Now you can call the function with a parameter:

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:

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:

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

Book Tip

Big Nerd Range Guide: iOS Programming: Excellent introduction to iOS development. Some programming experience is recommended.

Amazon