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 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 , 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”
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) . 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"
var myAgeOnFriday
var myAgeOnFriday : Int = 23
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.
let dateOfBirth: Int = 12011988
dateOfBirth = 12021988
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.
var myAgeOnFriday : Int
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.
// Declare an integer
var myAgeOnFriday = 23
// Declare a Boolean
var isUserLoggedIn = true
// Declare a String
var myStatusUpdate = "Today I won £300"
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 ?? = "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.
let π = 3.14159
let ?? = "dogcow"
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
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
var myStatusUpdate: String = "Today I won £300"
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.
var name = "iOS"
name = name + " Blog"
// This now outputs 'iOS Blog'
var firstName = "iOS"
var lastName = " Blog"
var fullName = "" // Blank but initialised
fullName = firstName + lastName
// This outputs iOS Blog
var flowerColour = "red"
var flowerType = "Tulip"
var sentence = ""
sentence = "The " + flowerType + " was " + flowerColour + " and looked amazing"
// Outputs:
// The Tulip was red and looked amazing
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
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
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")
}
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?
let str = "Hello, world!"
let reversed = String(str.characters.reverse())
print(reversed)
//Outputs !dlrow ,olleH
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.
var username = " userName01 "
username = username.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
print(username)
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 = "my$uperSec3rP@asswrd"
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.
let password = "my$uperSec3rP@asswrd"
let length = password.characters.count
print(length)
// Outputs: 20
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.
var isUserLoggedIn: Bool = true
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
0
.
var phoneTreeNames: [String] = ["John","Laura","Chris","Dave","Liam","Joseph"]
As mentioned previously if you are wondering about the Mutability of Arrays then the rules specified above are exactly the same.
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
print(phoneTreeNames.first)
print(phoneTreeNames.last)
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")
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!
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"
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.
phoneTreeNames.removeAtIndex(1)
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).
var children : [String: Int] = ["Rich" : 3, "John": 5, "Carl": 9]
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
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)
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.
children.removeAll()
print(children)
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
for (variable; condition; increment) { }
for (var counter = 0; counter < 6; counter++) {
print("Looped")
}
- Check if counter is less then 6
- If value is less than 6, add 1 to the counter
- Repeat until counter is 6
counter = counter + 1
counter++
counter = counter + 1
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
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
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.
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.
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)
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
var firstName: String
var lastName: String
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.
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
var myPerson= Person(firstName: "John", lastName: "Appleseed")
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.
func getAge(thisYear:Int, birthYear:Int)->Int {
return thisYear-birthYear;
}
let userAge = Person();
print(userAge.getAge(2016, birthYear:1988));
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 {
}
class Animal {
func sayHello() {
print("Hello")
}
}
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()