Swift Classes


Classes really are the bread and butter of object oriented programming (OOP). They are the building blocks of any applications which allow you to create "objects" to work with.

Essentially, a class couples together variables/contants and functions into one manageable package for you to work with.

Classes are abstract blueprints for the objects that your application needs to work with.

As a starting point:

  • Each class should be its own Swift file.
  • Classe should start with an upper case letter and are camel cased.
  • Classes start with the keyword class, the class name and then a set of curly brackets.
  • Everything goes inside these brackets.
class Person {


The above is a class decleration for a Person object. It doesn't do a lot at the moment, but already we can start creating Person objects in our application:

let someone = Person()

Lets expand the class to make it a bit more useful. Generally you can think of objects as being made up of two main components.

  • Its properties
  • Its methods (functions)


Lets start with adding some properties. Properties are simply constants and vairables within a class, think of them as the information associated with the object. For example sticking with our Person class, typically a person may have an age and an name:

class Person {

  let name: String!
  var age: Int!


Here we're saying that a Person has a name which is a String and an age which is an Int. We've declared a name as a constant and age as a variable, in our example a persons age can change, but once a name is set, they are not allowed to change it. At the moment, we will actully have a compile error, that's because name hasn't be given a default value. We could fix this by setting it as nil, but lets look at adding an initilizer to solve this problem:

init(name: String, age: Int) {
  self.name = name
  self.age = age

The init is a decleration looks a lot like a normal function, just without the keyword func. All classes get a default initilizer which we dont have to write, but would like like init(). The one we've writen above works exactly like a normal funtion, we are saying that we want to pass a name which is of type String and an age which is of type Int. We then assign those value we passed into the init to the respective propertive of the Person object.


You may be wondering what this self word is all about. Well, the constants that we pass into our init are called "name" and "age" which are the same names we gave our poperties. Within the init function "name" and "age" would reference the values passed into it opposed to the properties. Prefixing them with self make it clear were referencing the class properties.

Creating a Person

Now we have a very basic class setup we can start using person objects, technically called "instances". Creating one would look like this:

let someone = Person(name: "John", age: 20)

Creating an instance of our Person class looks a lot like creating any other vairiable or constant, we define it with let or var, give it a name and then use the initilized that we declared in the class, in the above example we now have a constant called someone, which is a Person object. You accessing properties of the object by using dot syntax. Here we'll simple print the persons name and because the age property was declared with var, we can change it to something else:

//Prints "John"

someone.age = 21
//Someones age will now be set to 21

Swift Methods & Functions

Methods & Functions

Methods and functions in Swift work similarly to many other languages, if you understand functions in another language, chances are it won't take you long to feel right at home in Swift.

Method vs Function

For simplicity here regard the words "method" and "function" as interchangable, as the keyword to define them is func I'll use the term "function" from here on.

Functions are simple a block of code that you have wrapped up and given a name to. They can be as long or as short as you like, this largely depends on how comple the task that the function performs is. Although it's generally a good idea to try and keep your functions as short and concise as possible, this keep things clear and managable.

Declaring a Function

A simple function might look something like this:

func saySomething() {

As you can see, they start with the keyword func, are then given a name (camel cased), a set of bracket, then a set of curly brackets which contain the body of the function. In the above example this simple prints the word "Hello".

Calling A Function

Once you have a function defined, you have to call it in order to execute it. Calling a function is straight forward, you just write the name of the function followed by a set of brackets. Calling the function we declared above would look like this:


This saySomething function can now be called time and time again to repete a task, performing the same action every time, in this case printing the words "Hello", but what if we wanted it to change slightly each time? This is where "arguments" come in...

Functions With Arguments

Arguments (sometimes called parameters) can be "passed" to a function to subtly (or in some cases dramatically) change how that function executes. Carrying on from our above example, the empty set of brackets after the function name signals that it currently accepts no arguments, lets change that.

Rather than printing the word "Hello" every time, let's give ourselves the ability to change the word that is printed. To do this we need to change the decleration of the function to accept a String:

func saySomething(words: String) {

Arguments come two parts, first a name, then the Type. The value of that argument then exists as a constant that we can use within the body of the fucntion. So here we print out words, which will be whatever value is "passed" to the function when we call it, which now looks like this:

saySomething(words: "Hello")

saySomething(words: "Something else")

Above, we're making two calles to the same function, but passing in different arguments. We can no longer call the function without any arguments as before, Xcode will tell us that we are missing an argument and offer us a Fix-it.

Note: As always Swift if obsessed with Type. This is a good thing, in the above example it means we can't pass an Int where the function is expecting a String. If we tried to do so we would get an error.

Swift Optionals


Swift is obsessed with everything being in a valid state. That is to say a for example String has to contain a valid string. It can’t be a number, or anything else (see Swift Type Casting) or even nil.

That is unless we mark the value as an optional. I’ll start by stating there is much more to be said about optionals than will be covered here, this is just the core concept.

Generally is you see an exclamation point (!) or question mark (?), it’s a safe assumption that you’re dealing with an optional value. Only in the case of a variable/constant being marked as an optional can it contain a nil value.

Optionals also have to have their type declared. Lets take a look at one:

  var name: String?

This creates a new name variable which can contain a String (and only a String) but but can be nil, and in fact is currently nil. We can then set this value at a later point in time just like any other value:

  name = "Kyle"

If we were to print this to our console at this point we would see “Optional(Kyle)”. That’s because we haven’t unwrapped the optional value.

Another way we could do a similar thing is:

  var name: String!

The difference between ? and !

? – Indicates that this value may or may not contain a value, it could be nil.

! – Indicates that by the time we come to use it, it will contain a valid value.

Swift Type Casting

Type Casting

Swift is a Type Safe language. That means that it is obsessed with what type of data is associated with what

When we declare a variable or constant, there are a few ways we can do it:

let someNumber = 5 

let anotherNumber: Int = 8

These lines essentially do the same thing (with the exception of the constant name and the actual number clearly). The extra syntax in the second example is simply declaring the type of data that ‘anotherNumber’ is going to be an Int value. One of the most useful bits of advice I got when I started learning swift is to read the colon as “is of type”. To that line would read as “The constant anotherNumber is of type Int and equals 8”.

That being said the preferred way is to leave the type declaration off and let swift infer the type itself. In this example its blatantly clear the ‘anotherNumber’ is an integer, so there is no need for the explicit type declaration.

Type safety is awesome! Why? Well it simply means that once a value is set we know what type of data it will contain. That means that A String will always be a String, never an Int or any other type of data.

Swift Variables & Constants

Variables & Constants


To create a variable in swift, you start with the keyword 'var', followed by your name (camel cased, because you're a good developer) and then a value:

var someWords = "Hello World"

Variables, as the name implies, can change over time. For example at a later point you could reassign the 'someWords' value:

someWords = "Something else"


Constants are declared very similarly to variables, except instead of 'var', you use 'let':

let name = "Kyle"

Again, as the name suggests, constants cannot change. Once they are set, they keep the value until they are deallocated.


So why would you ever use a constant, they’re like variables, but with restrictions, right? Yes, but there are two main reasons. Most importantly, it makes your intent very clear. By making something a constant, you are explicitly stating that this value will not change, ever. By using a variable, you are stating that, yes, this may well change when I use it again at a later point in time. Secondly, the compiler can make some slight optimisations for constantly.

Xcode will actually inform you if you have declared a variable and never changes it, and suggest you change it to a constant, and if you try to change a constant it force you to change it’s declaration to a variable.

Basically, just declare everything with ‘let’. When you try and change it Xcode will force you to change the declaration.