Introduction & Assumptions about you

Today I’d like to give you a tutorial on using Swift 3. I assume the following is true about you:

*** You are a beginner to Swift (or even programming in general)

*** You have a Mac or Mac virtual machine

*** You want to make epic iOS apps – but Apple documentation is just so dry and boring…

If at least two of the above are true then you’ll feel right at home in this tutorial. It’s quite long but it’s worth it to know the fundamentals of Swift! I thought I’d make it a bit more interesting than all the other tutorials out there by trying out something new. This article will be a mashup between written instruction and my own videos on YouTube. If you like it then please comment once you’re done, saying what was awesome and what sucked (nothing obviously…) 🙂

1 – Install Xcode

Well, this should be pretty obvious! Open up the App Store, find Xcode and install it. I don’t think you need a video to explain this!

2 – Create a Playground

A playground in Xcode is a little place where you can run code without compiling a full app. It’s great for trying out bits of code or for learning – which is what we’ll use it for at first. Open up Xcode and when you’re presented with the splash screen click ‘Create a New Playground’. When prompted, save it wherever you like.

[video_lightbox_youtube video_id=”tL7GJpU9M6Y&rel=false” width=”100%” height=”auto” anchor=”click me” auto_thumb=”1″]

3 – Variables

Variables are the building blocks of your application. A variable can hold anything you like from numbers, characters (known as strings) to much more complex data. They help to keep track of where and what stuff is in our application. EVERYTHING you do with ANY programming language uses variables! Variables are usually defined by ‘type’ – that means a variable can only hold a certain type of item. For example that could be a number, a string, a URL etc. Create a String variable in your playground like this:

Notice that the playground shows you your variable on the right hand side? This is not a normal programming feature – it’s just a playground feature. It allows you to see what is being declared at a glance. The other thing that we see is the line ‘import UIKit’. This means that we’re importing a bunch of code from the UIKit class – it’s needed so that our playground understands what we’re typing and doing.

[video_lightbox_youtube video_id=”SR9rStPLWko&rel=false” width=”100%” height=”auto” anchor=”click me” auto_thumb=”1″]

4 – Collections / Arrays

Arrays or collections store ordered sets of variables. Let’s say I have a list of numbers – instead of creating the variables one by one I can just create one array to hold them all! Clear your playground code (but leave the UIKit import in) and create an array of integers (whole numbers):

The universal symbol for arrays tends to be in the form of square brackets [] with which we surround the variable type (Int in this case). At the moment the array is empty, all we’ve done here is to bring it into existence (known as initialising). This array can only hold integers (whole numbers) though. What if we wanted to hold strings? Create another array to hold strings:

So doesn’t it beg the question…what if we want to put some values into these empty arrays? Well that’s easily done:

Appending is how we add items to arrays! If you’re completely new to programming the ‘append()’ that you see is called a function. That just means that it’s a bit of code that executes, in this case adding an item to the array. Try to put a number into the ‘someStrs’ array to see what happens:

BANG! This showed you all kinds of red errors didn’t it? This is because arrays can only hold one type of variable! This adding one by one is tedious though – let’s speed up the process with some programming shortcuts (these might work in other languages too):

You should see the contents of the array printed out on the right side of the playground. However, in most cases you’ll just want to declare arrays in one line, maybe including all the contents there and then. Change your someInts declaration (the first line) to:

It doesn’t really matter how you declare your array, but try to be consistent – it will make your life easier! You will normally need to count your array elements (I’ve never built something where this isn’t the case!). To count the elements simply use the ‘count’ property:

Finally, accessing elements is easily done by using an index. An index starts at 0 (IMPORTANT!). If you want to access element number one you would use index 0. Getting this wrong is the MOST common error out there. Access the first and third elements in your array:

Those are the basic building blocks you need to manipulate arrays!

[video_lightbox_youtube video_id=”WiiW0ky8Q-0&rel=false” width=”100%” height=”auto” anchor=”click me” auto_thumb=”1″]

5 – Collections – Sets

Sets are similar to arrays but with ONE MAJOR DIFFERENCE! Sets have no defined order. This has a major connotation for your programming – sets only only allow one of any particular variable to exist in them. For example, if we added ‘ford’ to a set called ‘cars’ and then added it again later ‘ford’ would only appear once in the set! Let’s create a couple of sets to hold characters or strings as well as inserting items into them:

Look at the variables output on the right hand side. For the letters Set we get “a”. For the favs Set though we only get 3 elements (even though we added 4 when creating it). The problem? We added “wine” twice and the Set ignored the second addition! Be very careful when using sets!

[video_lightbox_youtube video_id=”2WQTzI5Wo5A&rel=false” width=”100%” height=”auto” anchor=”click me” auto_thumb=”1″]

6 – Dictionaries

A dictionary stores associations between keys and values, just like a dictionary! There is no defined order because you don’t need it. Create a dictionary like this:

So now we have a dictionary, yay! However, dictionaries are intended to have multiple items under each key (similar to a language dictionary where you would look up “a” for words beginning with “a”. Adding extra entries is easy enough:

Finally, we can look up entries in dictionaries:

By the way double slashes means that this is a comment (in green). Xcode doesn’t read comments – they’re for us to understand what we’ve just done. The question mark is to do with optionals…it basically says, “only try to get element [1] if the key [2] exists. Optionals save us from the most common kinds of errors in other languages. We’ll cover them later on this page.

[video_lightbox_youtube video_id=”gWdMkEA3Hrc&rel=false” width=”100%” height=”auto” anchor=”click me” auto_thumb=”1″]

7 – ‘If Else’ and ‘Switch Case’ Logic

Sometimes we want to check various things related to variables or other pieces of information. If you have a ‘car’ object you might want to check how many wheels it has. For this we can use ‘if else’ and ‘switch case’ statements. ‘if else’ statements work like this:

First we check if something is true. Is my age equal to 33? If that’s the case then the code inside the curly braces gets executed and the other code sitting in ‘else if’ and ‘else’ does not. Try changing the age to 32 or 64…what do you notice? The other items should get printed instead! Of course this is kind of messy if we have long checks to perform so a better way in that case is to use a ‘switch case’ statement:

‘switch’ declares the variable we’re looking at (myNum in this case). ‘case’ takes care of each eventuality and ‘default’ says what should happen if nothing is true from all the cases. Pretty similar to if else statements but a little neater!

[video_lightbox_youtube video_id=”txTsMCTwKas&rel=false” width=”100%” height=”auto” anchor=”click me” auto_thumb=”1″]

8 – Round and Round with Loops

Loops are a fundamental part of all programming languages. They enable you to execute something multiple times. Why is that important? Let’s say you have an array of items and want to print all of them out. Doing that manually one by one would be mighty painful! The solution is go through each element of the array. Let’s create a basic loop that counts from 1 to 10 and prints it out:

This block of code creates a variable called ‘i’. The ‘for’ loop prints out ‘i’ whilst it is between 0 and less than 10. Each time it goes round ‘i’ is automatically increased by 1. This is called a ‘for’ loop because it does something ‘for’ a set number of times. Now let’s do something useful, create an array and loop through all of its members:

This will create a variable called ‘n’ for each member in the array and print it. Can you see how this would be useful in a real life programming situation? Arrays, collections and sets are so often used that loops are also always present! There is one final loop you need to know about, the ‘while’ loop:

If you did the above notice that the loop goes on FOREVER! You are stuck in an infinite loop (which is also Apples address – 1 Infinite Loop!). What’s happening is that we’re checking if ‘count’ is less than 10, which it is every time! We need a way of incrementing count each time we go around the loop. Modify your code:

‘count++’ increments count by just 1 each time it goes around. It’s a handy shortcut, equivalent to saying ‘count = count + 1’. You’ll find that shortcut in most languages. There is one other loop called a ‘repeat while’ loop. It’s pretty rare that you’ll use it so check out the video if you want to know more.

[video_lightbox_youtube video_id=”J321lXiftP0&rel=false” width=”100%” height=”auto” anchor=”click me” auto_thumb=”1″]

8 – Functions

Functions are a fundamental concept used to order our code. Let’s say we had one of the loops above but we didn’t want to rewrite that loop each time we needed to use it. How would we go about that? The answer lies in functions…they are simply a grouping of code that can be executed when called. Create a function by transplanting the code from the section above into a new function:

A function is never called by default – we have to manually do it (in the last line). Functions serve to organise our code and save us from repeating ourselves! This is by design – if you ever catch yourself repeating code think, “Can I move this to a function?”. Functions can also take variables if needed – these are called arguments (I’ve never known why…). Let’s set our function up to take 2 arguments, one for a message to display and another for the number of counts in the loop:

This sends over a message and a maximum count. In the function itself we tell the loop to go around the number of times specified by the input argument ‘pCount’ and we also print out the message “not finished yet” until that loop exits. Try modifying the pCount in your own playground to see the effect on number of loops that are performed. The final important thing to know about functions is that they can return something. Change your code to return a string:

The ‘String’ part tells us that the function will always return a String. Inside the function the loop execute until it is finished and then executes the ‘return “done!” ‘ line. This sends back the string “done!” to the original calling of the function (ie, the last line in the above code. That is why the last line outputs “done!” on the right side of your playground! Returning objects is used ALL THE TIME in programming. A great example is if we fetch data from a database and return it to the place where it was requested!

[video_lightbox_youtube video_id=”DKVVqYvkx0E&rel=false” width=”100%” height=”auto” anchor=”click me” auto_thumb=”1″]

9 – Optionals

Optionals are THE MOST misunderstood thing in Swift – by far! To understand them you need a little bit of history. Back in the good old days you could create a variable (in any language) without assigning a value to it – so you could just have ‘myVar’. Fine…except that if you tried to use that variable you’d be in major trouble because there is nothing contained in it! Remember, a variable is just a box that contains something – the box could be empty! Remember stealing cookies and leaving the empty box for your mother to find later on? There is hell to pay when that happens and it’s the same in programming!

The best advice concerning variables was always to check that they existed before using them (called a null check) but hey, programmers can get lazy right? Occasionally we would just skip the check because our code is awesome and will never try to use a null variable…but this never turned out well in practice! Ever had a program just crash instantly? Probably a null variable error. Therefore Apple decided to banish the problem once and for all with ‘optionals’. An optional is a variable that either contains something or nothing. Optionals are automatically checked within Xcode before the app is compiled – avoiding probably 90% of future errors. Nice and handy! Let’s see how they work in practice:

So to make something optional simply add a question mark. In this case trying to print it gives us back nil because nothing is inside the optional. Create a ‘null’ error by trying to add another string to the one above:

All we did here was try to add a string to the end of myStr. It didn’t work because myStr is nil! Swift checked the optional before we compiled the application and found nothing – preventing us from shipping bad code! In other languages this error wouldn’t surface until a user tried it and…big crash! Of course there are ways around this, we can skip the optional check by using an exclamation mark:

An exclamation tells Swift there is DEFINITELY a variable inside this optional so Swift lets the optional check pass by. Of course this would crash if a user executed the code in an app! Use exclamation bypasses very carefully, if at all – although there are places where it is OK to use them. As you get more familiar with Swift these will become obvious. So how do we run the original optional code to check for values vs nil? By using an ‘if let’ statement:

We can use the familiar ‘if’ logic to see if the optional actually contains a variable. The ‘let’ part declares a new variable called myStrVal which contains the value of myStr. If this line works then the program proceeds onto executing the code.

[video_lightbox_youtube video_id=”A68igkYr8tc&rel=false” width=”100%” height=”auto” anchor=”click me” auto_thumb=”1″]

And that’s your gentle introduction to Swift programming language 🙂 Leave me a comment if there’s something you didn’t understand or if there’s anything else you’d like to learn in Swift!

Learn Swift Programming in 10 Steps – An Article and Video Mashup

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share This

Exhausted by your 9 - 5?

Would you prefer to work for half the time and earn double? The first step to your freedom is understanding how apps make money. Simply enter your email below and I will send you a free PDF describing the process.

If you're serious about improving your life then do not miss this opportunity.

You have subscribed! Please check your email to confirm this subscription and to receive your item!