Show Menu

Do you have a job opening?

Submit your 30 day Job Listing for FREE

Swift Tutorial

This Swift Programming Language tutorial is aimed at people with no Swift programming knowledge. It is designed to take you form the beginner level to mid-app developer. Have you ever wondered how to make an app? or had that great idea but had no way to start creating it? Well.. I Will Go through the basics of the syntax and point you in the right direction to creating your first Swift Application

UPDATE 01/07/2016
This Swift Tutorial has been updated to accommodate Swift 2. The new version of the Swift Programming Language.

Jump to:

What is Swift?

In late 2014 Apple released a new programming language to create iOS and OS apps, this language is if you have not already guessed called Swift. Taken from Apple’s [1] own website:

Swift is an innovative new programming language for Cocoa and Cocoa Touch. Writing code is interactive and fun, the syntax is concise yet expressive, and apps run lightning-fast. Swift is ready for your next iOS and OS X project — or for addition into your current app — because Swift code works side-by-side with Objective-C.

Now, Apple have brought us Swift 2, the stronger, faster, smarter version of the Swift Programming Language.

“We’re stepping on the gas this year with Swift 2” said Apple’s Craig Federighi on stage at the 2015 WWDC keynote. “Swift 2.0 adds a bunch of features that developers have been asking for, to ensure that apps written in Swift are faster and can do more” [2]

Variables

Dynamic Variables

Variables in Swift 2 are a way for you to create dynamically assigned values. Dynamic means that the value you have set can change. To set a variable in Swift 2 you would prefix your variable name with the word var. This then tells Xcode that you are declaring a variable to use. The name for the variable that you set is a way for you to reference the value you want to set and use. The standard convention for declaring variables in Swift is to use camel case (Wikipedia) [3]. Camel Case means that if you use several words to declare a variable, the first word will start with a lower case and the words after that will start with an uppercase.

Lets say you wanted to created a variable that would reference your age on Friday. You would do this like so:


var myAgeOnFriday

Finally, the next thing we need to do to this variable is to specify the value. So let’s say on Friday you’re going to be 23 you then need to add the following and you have successfully declared a variable called myAgeOnFriday with the value of 23.


var myAgeOnFriday : Int = 23

In the above Swift 2 Dynamic Variable declaration the equals operator = initializes the variable with that value.

To assign a String to the Dynamic Variable, You would do it like so:


var myName : String = "Mark"

Constant Variables

So we have covered how to create dynamic variables in Swift and how you can change them. But what if you wanted to use a variable that you knew was not going to change? For example the date you were born. For this we can use a constant. Declaring a constant in Swift is a little different than the usual variable declaration of var instead we use let. So to declare a constant in Swift we would write:


let dateOfBirth: Int = 12011988

Constants are only meant to be used with values that you are 100% sure will not change and if you tried to edit them later on you will get an error. So let’s say that we decided we were born on another day and wanted to change that constant after we have defined it like so:


dateOfBirth = 12021988

You will get this error: Cannot assign to ‘let’ value ‘dateOfBirth’. This is just Xcode saying that the value is set using let and that it is a constant that cannot be changed.

Type Annotation

Because Swift is a type safe language it’s better (best practice) to create an explicit variable. This means you tell Xcode what type of variable is going to be used. After the above declaration you would follow that with a colon : and then declare the variable type.

If you have a variable that is going to be an integer, like myAgeOnFriday you would write:


var myAgeOnFriday : Int

This is basically saying declare a variable called myAgeOnFriday of type integer.

Type Inference

So, the way that I have shown you so far is to declare your variable by giving it a name and then defining the type of variable: Int, String, Bool. However, This is only the best practice and you do not need to do this. Swift is clever enough to know what type of variable you are wanting to create just by the way you define the value (value is the assigned data at the right side of the equals sign). For example if you wrap the value in “value” double quotation marks then Swift will know that this value is a String. So using the above defined variables this is how you can define them without using the Swift explicit variable option:


// Declare an integer
var myAgeOnFriday = 23

// Declare a Boolean
var isUserLoggedIn = true

// Declare a String
var myStatusUpdate  = "Today I won £300"

As you can see, the colon and the declaration of type (Int,String,Boolean) is no longer required. This can save you a lot of time.

Variable Naming

A little bit above I mentioned the naming convention of Camel Case. Now, this is a naming convention, but you can actually name your variables anything, even using Unicode characters:


let π = 3.14159
let 你好 = "你好世界"
let ?? = "dogcow"

As you can see in the above examples, we have not used Swift Type Annotation when declaring our variables. This is because you don’t have to. It’s just better practice to do so.

Swift String Mutability

This might sound weird or even scaring but it is nothing to worry about. I’m only adding this section in briefly as I’ve seen a lot of people refer to the term String Mutability. When I first started coding I was very unfamiliar with this. So Succinctly here is the Explanation taken from Apple [3]:

You indicate whether a particular String can be modified (or mutated) by assigning it to a variable (in which case it can be modified), or to a constant (in which case it cannot be modified which makes it immutable)

Integers

Integers in Swift are a whole number which can be positive or negative. As you can see in the above declaration you would initialise an integer in Swift with Int.

Floats

A Float is basically an integer with a decimal place in it, for example 1.23. Setting a float variable in Swift is pretty much the same as setting an integer however you use the word Float. Let’s say you had loan amount that you borrowed and you needed to set this at the top of the code. You would do this like so:


var myLoanAmount : Float = 3500.37

Strings

A String is a collection of ordered characters and can be made up of both integers and letters. For example you could have:


var myStatusUpdate: String = "Today I won £300"

You might see empty strings being declared in code and this is usually because the coder has wanted to define all the variables at the beginning so that its easier to add and append things to them. Here are some examples:


var emptyString = ""               // empty string literal
var anotherEmptyString = String()  // initializer syntax

String Concatenation in Swift

Concatenating strings is a way to join two or more strings together. This comes in very useful when you are gathering peoples names for example.

Let’s say that you have a variable called name:


var name = "iOS"

Which only has the first name but you want to assign a last name also. Because the variable as already been initialised you can simply just type the variable name and add it to itself.


name = name + " Blog"
// This now outputs 'iOS Blog'

Why would you do this? This might be very useful especially if you get the first name and the last name from different views and at different points throughout the application process.

You can also add two variables together like so:


var firstName = "iOS"
var lastName = " Blog"
var fullName = "" // Blank but initialised

fullName = firstName + lastName

// This outputs iOS Blog

You can also add in String variables and text and concatenate them together, like so:


var flowerColour = "red"
var flowerType = "Tulip"
var sentence = ""

sentence = "The " + flowerType + " was " + flowerColour + " and looked amazing"

// Outputs:
// The Tulip was red and looked amazing

If you wanted to add in any variable, integer or String into the ‘sentence‘ variable you can do so if you wrap it in \(variable). This is called Swift String interpolation and here is an example:


var myAge = 23
var event = "Party"
var sentence = ""

sentence = "Yesterday I was \(myAge) and I had an awesome \(event)"

// Outputs
// Yesterday I was 23 and I had an awesome Party

If you try to add an integer into the string variable above you will get an error. Let’s give it a go: If you replace \(myAge) in the above variable statement with ” + 23 + “ you will get this error: UInt8 is not convertible to String.

Capitalize Words in Strings

What is you wanted to display the first character of every word in a sentence with a capital letter? The Swift Programming Language gives us capitalizedString to do just that. You will need to declare a new variable and pass in the variable you want to capitalize with capitalizedString appended. Like so:


var originalString = "This is a sentence, thankfully."
let capitalizedString = originalString.capitalizedString

print(capitalizedString)
// Outputs: This Is A Sentence, Thankfully

Check if String is Empty

There might be a time, especially when you are validating form fields that you need to check whether a string is empty or not. Luckily, Swift gives us a nifty fix for this called: isEmpty. You need to add this as a condition in an if-else statement:


var yourString = "Hello World!"

if yourString.isEmpty {
    print("Oh dear, this string is empty")
}
else {
    print("Nope, it's not empty")
}

How to reverse Strings in Swift

Introducing swift reverse(). For a little bit of fun I will show you how to do this. I have not found a professional use for it yet, but you never know.


let str = "Hello, world!"
let reversed = String(str.characters.reverse())
print(reversed)

//Outputs !dlrow ,olleH

Quite fun, right?

How to trim Strings in Swift

What we mean by trimming a string in Swift is to remove the white space at the beginning or the end of the string. This might not seem useful but think about it, How many times have you tried to log into a website and kept getting an error, wrong username or password. Only to realize you have pressed the space-bar and added in a space which the system counted as a character? Now you see the important.

So here is how we trim white space in Swift:


var username = "  userName01     "
username  = username.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

print(username)

Pretty useful right? You will remember this one for a while. You’re Welcome.

How to get the length of a string in Swift

This is useful if you want to set a minimum length of a password for example. Swift gives us characters.count which will count all the characters, even white space:


let password = "[email protected]"
let length = password.characters.count

print(length)
// Outputs: 20

You would use this with an If-Else Statement to check the length complies with your prerequisite.

Boolean

Booleans are a fantastic type of variable that you can set. This variable will return the value of either trueor false and to set it you use the Bool declaration after the colon in your variable, like so:


var isUserLoggedIn: Bool = true

As you can probably gather from the variable name set above a Booleanis a nifty way to assign a value that you can check against. So above the variable name is: isUserLoggedIn – We can perform a check on this using an if-statement (We will cover if-statements later on down the article) to see if the user is logged in. This is very handy to be able to show different views or options for users that are not logged in or those that are.

Swift Arrays

We know how to create a variable for a name, but lets assume that you are running a phone call tree and you have a list of 23 and growing names. Adding new lines for every single name is going to be tedious. So what is an Array? Well its basically a way to hold many variables in a specific order. An Array will assign each Value an index value. It’s important to know that the index values in Arrays start at 0.

Taking into account what I just mentioned that the list is for a phone call tree and that we do not know how many people will be in the list we can create an Array like so:


var phoneTreeNames: [String] = ["John","Laura","Chris","Dave","Liam","Joseph"]

As you can see, we have started with the declaration of a variable: var. and then specified the array name: phoneTreeNames and then the type inference of: String however we do not need to specify the type, just like we don’t when declaring variables in Swift.

As mentioned previously if you are wondering about the Mutability of Arrays then the rules specified above are exactly the same.

As mentioned at the beginning of the Array section each Value in the Array will have an automatic index value assigned to it. We can use this to get the item out of the array like so:


var phoneTreeNames: [String] = ["John","Laura","Chris","Dave","Liam","Joseph"]

print(phoneTreeNames[3])
// Outputs: Dave

Get the First and Last items in Array

The new update to the Swift Programming Language allows us to find the first and last items in an array by using, you guessed it first & last:


print(phoneTreeNames.first)
print(phoneTreeNames.last)

So, how many names are in this Array? If you need to get the total value of these arrays at any time you can call the count function. Like so:


print(phoneTreeNames.count)
//Outputs 6

// Or you could assign it to a variable
let totalInArray = phoneTreeNames.count
print(totalInArray)
//Outputs 6

Append items into Array

You can append items to the array using the append method, providing that it is mutable. This means that you have declared the array with var not let.

You can do this quite easily, like so:


phoneTreeNames.append("Simon")

Change items in the array

If you are wanting to change the name in an array, then you can modify it using the allocated array index value.
Let’s say you want to change the name Laura in the above array that we have been using, which is in the second position of the array but has an index value of 1. Remember I said that arrays start their index value at 0. You would do this like:


phoneTreeNames[1] = "Jeremy"

Goodbye Laura and Hello Jeremy, Snap!

Delete items from the array

Oh no, Jeremy has now decided to leave the phone tree and now you have to remove him from the list. No problem. Again, we will use the array index value but this time pass it as a parameter to the Swift removeAtIndex(*) Function:


phoneTreeNames.removeAtIndex(1)

All done. He has now been removed from the list.

Dictionaries

In Swift, you can store associates Key and Value data in dictionaries. A quick way to remember this is just think about a book. The table of contents is the key and the page is the value. Dictionaries do not sort or organise your data in any specific order and to get the Value you need to reference the Key. Let’s say that you have three children (Rich, John and Carl) and you want to store their ages (3,5,9) respectively. You would do this like:


var children : [String: Int] = ["Rich" : 3, "John": 5, "Carl": 9]

As you can see in the example above, We have declared a Dictionary by typing var children :. We have then declared the type inference for the Key as String and the Value as Integer: [String: Int] and then we have added the values: = [“Rich” : 3, “John”: 5, “Carl”: 9]. Each of the Keys (the names) have the corresponding value (their ages).

Access Value in Dictionary by Key

Ok, so now lets assume you forgot one of your child’s ages and you need to query that from the Swift Dictionary we talked about above. It’s pretty simple, providing you have not forgotten your child’s name also:


print(children ["John"])

//Outputs 5

Delete from Dictionary using Key

Now, we’re going to assume that the aforementioned child called John has been to much to handle and you have sold him for some bread, milk and fifty shillings and you need to remove him from the Dictionary, Although I don’t condone child sale I will show you how to remove an item from the dictionary by using the key:


children.removeValueForKey("John")

// Now view your remaining children 
print(children)

Remove all from dictionary in Swift

Ok, since the sale of John your other children have become unruly, so much so you’re sat there thinking about the days you wanted to travel, the days before the children. Well, the solution here is just to remove them all:


children.removeAll()

print(children)

And Voila, you’re free.

Swift Loops

Loops in Swift allow you to iterate over pieces of code and perform actions on them.

Swift For Loop

One of the more common loops in Swift is the For-Condition-Increment (‘For loop’ for short). This loop follows this format:


for (variable; condition; increment) { }

The variable is often an integer that is used to keep track of the current number of loops iterated. The condition is checked after each loop; if it is true, the loop runs again. If the condition is false, the loop will stop running. Last but not least is the increment which is the amount added to the variable every time the loop executes.

Take the following code:


for (var counter = 0; counter < 6; counter++) { 
    print("Looped")
}

The variable: counter is currently set to 0 and the condition is saying if the counter is less < than 6. The increment will add 1 to the value of counter $counter++.

So when you run this code it will run through like so:

- Get the value of var counter
- Check if counter is less then 6
- If value is less than 6, add 1 to the counter
- Repeat until counter is 6

Most increments are written using a common shorthand practice:counter++. Normally, to increment a variable by one, the syntax looks like this:


counter = counter + 1

This code takes the counter variable and sets it equal to the counter variable plus one. This increases the counter value by one each time it is executed. However you can use this shortcut in Swift. Adding ++ to the end of a variable name to increment it by one. For example:


counter++

This is exactly the same as:


counter = counter + 1

You can do a lot with counters, check out how to create a counter application with Swift NSTimer

Swift Repeat-While Loop

A Repeat-while loop is similar to a for loop in that it runs with a condition. Lets say you have a game, and for every player who's score was under the next level target, lets say 100, you could print a statement for everyone of them


var playerID = 0
repeat {
    print("The Next Level !waits!!")
    i++
}
while playerID < 100

Swift Guard Statement

Using if-let often you need to do a lot of work within the scope of the braces that follow the statement or pass a value back to another optional. With guard you deal with the else statement first for what happens if the statement fails, after which you have access to the value(s) in non-optional form.

Check out our introduction to Swift Guard statement for a more exhaustive explanation and implementation.

Swift Enums

An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code. As of Swift 2, the Swift Enums can now support multiple types and have some additions to Raw Values. Pretty swanky eh :)

Check out our guide to the Swift Enum

Classes in Swift

Classes are general-purpose, flexible constructs that become the building blocks of your program's code. You define properties and methods to add functionality to your classes by using exactly the same syntax as for constants, variables, and functions.

To define a class in Swift, we start with the declaration of Class followed by the name that we want to call it. In this example, We're going to call it Person. So, lets declare our first Class in Swift:


class Person { }

Unlike other programming languages, Swift does not require you to create separate interface and implementation files for custom classes and structures. In Swift, you define a class or a structure in a single file, and the external interface to that class or structure is automatically made available for other code to use. [5]

Class Properties

Just like most OOP (Object-Orientated Programming) Languages, Swift can have properties.

Properties associate values with a particular class, structure, or enumeration. Stored properties store constant and variable values as part of an instance, whereas computed properties calculate (rather than store) a value

Lets create some properties in Swift for a person called John Appleseed.


var firstName: String
var lastName: String

The above properties are also known as stored properties. Make sure these are in the Class declaration.

We can now call any of this like so:


let myPerson = Person()

print(myPerson.firstName)
print(myPerson.lastName)

Swift Class Initialization

In the above example, we declared two strings, This means the class must have values for those. If not we will get errors, so now we need to set an initializer:


init(firstName: String, lastName: String) {
        self.firstName = firstName
        self.lastName = lastName
    }

Now we can call it like so:


var myPerson= Person(firstName: "John", lastName: "Appleseed")

You could always use the ? operator after your variables to negate the need to use the initializer.

Class Methods

Methods, also known as functions are a way to add functionality to your Classes. The term method is usually used instead of function in the context of classes. Defining a method is almost identical to defining a function.

Now, I'm going to show you how to define a method, I will show you how to calculate someone age from their birth year:


func getAge(thisYear:Int, birthYear:Int)->Int {
    return thisYear-birthYear;
}

What this function will do is take two values, one for thisYear & birthYear. Then it will subtract (-) one from the other, the result will be their age. Simply adding this function will not do anything, we need to initialise the class first:


let userAge = Person();

Now, we can pass two values to the method and print out the result like this:


print(userAge.getAge(2016, birthYear:1988));

This will output 28.

Class Inheritance

In the Swift Programming language a class can inherit methods, properties & many other characteristics from another class. When one class inherits from another, the inheriting class is known as a subclass, and the class it inherits from is known as its superclass. Inheritance is a fundamental behavior that differentiates classes from other types in Swift.

Lets create a Parent Class. This is known as just a regular class until it inherited:


class Animal {
    func sayHello() {
       print("Hello")
    }
}

Now we will create a subclass called dog that will inherit Animal:


class Dog : Animal {

}

We now need to create a new Dog instance:


let myDog = Dog()

Finally, to access the methods in the parent class, we would simply write:


myDog.sayHello()

How to make an iPhone app

Now that you have a good understating of the Swift Programming language you are probably thinking how do I make an app? Well, don't fret. We have some rather great examples of how to build an app.

References

having issues?

We have a Questions and Answer section where you can ask your iOS Development questions to thousands of iOS Developers.

Ask Question

FREE Download!

Get your FREE Swift 2 Cheat Sheet and quick reference guide PDF download when you sign up to SwiftMonthly


Sharing is caring

If you enjoyed this tutorial, please help us and others by sharing using one of the social media buttons below.


iOS-Blog Admin Team

Written by:

We're here to help.

Comments

comments