Why Swift?

In June 2014, Apple first introduced Swift, a general-purpose and modern programming language. Since then we have seen a lot of changes to the languages, like being open sourced, and releases of versions 1, 2 and 3. It has come to light that Swift was in the works since 2010 because Apple saw the limitations of Objective-C, a language almost 30 years old, and decided it was time for a change. However, in true Apple fashion they did not want to release a half-baked language. They realized that no matter the drawbacks of Objective-C they could still push the envelope with it and so they did. It’s been almost a decade since the release of the first SDK and 1.2 million apps have been submitted to the app store. Millions of developers have suffered through the learning the arcane syntax and limitations of Objective-C.

Swift probably took a little over four years to create and is the result of the work of many smart individuals who love crafting a new language. They looked all around for inspiration and not only created a new language, but the tools to go along with it that would make it easy to learn. When talking about Swift, Apple refers to three key considerations: safe, modern and powerful. It lives up to all those three things. Outlined below are some of the very basics you need to get up and running with Swift. If you already know a programming language then you will see a lot of similarities with other modern languages. You might even wonder why they had to invent a whole new language but that is a discussion for another blog post.

Using Swift

Firstly, you will have to download and install Xcode. Once you have installed it then open it up and select File from the menu -> New -> Playground. Give your playground a name and under platform select iOS. If you don’t have a Mac then you can download Swift Playgrounds for your iPad.

Note: This blog post is available as an Xcode Playground which you can download here.

Fundamentals

Variables

As with every programming language you have variables which allow you to store data. To declare a variable you have to use the keyword var.

var greeting: String = "Hello World"

The above code instructs the system that you want to create a variable named greeting which is of type String and it will contain the text, “Hello World”.

Swift is smart enough to infer that if you are assigning a string to a variable and in fact that variable will be of type string. So you need not explicitly specify the type as in the above example. A better and common way of writing the above example would be:

var greeting = "Hello World" // Inferred type String

Variables can be modified once created so we could add another line and change our greeting to something else.

While writing an application there are many instances where you don’t want to change a variable once it has been initialized. Apple has always had two variants of types mutable and immutable. Mutable meaning the variable can be modified and immutable that it cannot be modified. They prefer immutability by default which means that the values aren’t going to change and it makes your app faster and safer in a multi-threaded environment. To create an immutable variable you need to use the keyword let.

If we change our greeting example to use let instead of var then the second line will give us a compiler error because we cannot modify greeting.And we can no longer call greeting a variable since we are using the keyword `let`. It is called a constant because it cannot be modified.

The above example not only shows us the various types that are available in Swift but it also shows us that the reason to use let. Aside from the version number of the Swift language everything else remains constants. You might argue that isAwesome is debatable but I’ll let you reach that conclusion once you reach the end of this post.

The title and review strings are joined together and the resulting string is assigned to the constant description. The joining of strings is known as concatenation. There are times when using the + operator to concatenate is cumbersome, at times like these we use something known as string interpolation. This powerful feature allows us to use variables inside of double quotes which eventually are replaced by their values.

let datePublished = "June 9th, 2014"

let postMeta = "Blog Post published on: \(datePublished)"

// postMeta = "Blog Post published on: June 9th, 2014"

The resulting postMeta string will contain the value of datePublished along with the rest of the string. The same string could have been written using the plus operator but this way is a lot cleaner and concise.

In all the above examples we have been using the keyword let which means you cannot modify the string once it has been created. However, if you do need to modify the string then simply use the keyword var.

Numeric Types

Besides strings you have Int for whole numbers. Double and Float for floating-point numbers and Bool for boolean values such as: true of false. These types are inferred just as a string so you need not explicitly specify them when creating a variable.

A Float and Double vary in precision and how large of a number you can store.

Float: represents a 32-bit floating-point number and the precision of Float can be as little as 6 decimal digits.

Double: represents a 64-bit floating point number and has a precision of at least 15 decimal digits.

By default when you write a floating-point number it is inferred as a Double.

var version = 1.0 // inferred as Double

You can explicitly specify a Float.

var version: Float = 1.0

Collection Types

Array

A collection contains multiple items that can be accessed via subscripting. There are two main types of collections: array and dictionary. An array is an indexed collection of identically typed data items and can be accessed via an index beginning with 0.

You might have noticed that in my description above, I mentioned that an array has “identically typed items”. In Objective-C, you can store any number of types in a single array. The common theme amongst Swift is that it is a safe language, which means that an array of strings is just that, an array of strings. You cannot add any other type into the mix.

To access an item from the array you need to use the subscript:

let firstCard = cardNames[0]

The above line instructs the system to access the first element in the array and assign it to the constant named firstCard.

Modifying an Array

Lets create a new array that contains a todo list.

var todo = ["Write Blog","Return Call"]

Make sure that you use the keyword var so that we can modify our array.

To add another item to our todo array we use the ‘+=’ operator:

todo += "Get Grocery"

To add multiple items to our todo array we simply append an array:

todo += ["Send email", "Pickup Laundry"]

To replace an existing item in the array simply subscript that item and provide a new value:

todo[0] = "Proofread Blog Post"

To replace an entire range of items:

todo.count

Dictionary

The other collection type is a Dictionary which is similar to a Hash Table in other programming languages. A dictionary allows you to store key-value pairs and access the value by providing the key.

For example, we can specify our cards by providing their keys and subsequent values.

var cards = ["Jack" : 11, "Queen" : 12, "King" : 13]

Above we have specified the card names as the keys and their corresponding numerical value. Keys are not restricted to the String type, they can be of any type and so can the values.

To access a specific card we can subscript the key to retrieve its value:

let jack = cards["jack"]

Modifying a Dictionary

What if we wanted to add an “ace” to our cards dictionary? All we have to do is use the key as a subscript and assign it a value. Note: cards is defined as a var which means it can be modified.

cards["ace"] = 15

We made a mistake and want to change the value of “ace”. Once again just use the key as the subscript and assign it a new value.

cards["ace"] = 1

Control Flow

Looping

What it good is a collection if you cannot loop over it? Swift provides while, do-while,for and for-in loops. Lets take a look at each one of them.

The easiest one of them is the while loop which states while something is true execute a block of code. It stops execution when that condition turns to false.

while !complete {
println("Downloading...")
}

Note: the exclamation mark before the variable complete denotes not and is read as “not complete”.

This is the first time we are using the print function. It essentially prints out whatever string is provided to it within the parenthesis.

Likewise, you have the `repeat-while` loop which ensures that your block of code is executed at least once.

If Statements

Note: The if syntax can have parenthesis but they are optional. However, the braces {} are mandatory unlike other languages.

Switch Statement

The switch statement in Swift is very versatile and has a lot of features. Some basic rules about the switch statement:

It doesn’t require a break statement after each case statement

The switch is not limited to integer values. You can match against any values such as: String, Int, Double or any object for that matter.

It must be exhaustive which means that it must match against every value possible, if not, you must have a default case. If you don’t provide a case for every value or a default then you will get a compiler error saying: “switch must be exhaustive”.

What if we simply wanted our function to build a string and return the value instead of printing it? Then we can specify a return it which is specified at the end of the function declaration followed by an array ->.

Above we are saying that we are creating a function named buildCard which takes in two parameters and returns a String. The return keyword is important without it you will get a compiler error. The return statement requires a value and in our case we are returning a string. We would use this function as such:

let card = buildCard(cardName: "Jack", cardValue: 11)

Conclusion

If you have made it so far then congratulations you are now familiar with the basics of Swift. That is a lot to take in but it is only scratching the surface and what Swift is capable of. This blog post assumes you have some familiarity with programming concepts. If you are completely new to programming then our Swift Basics course walks you through the basic concepts of coding while teaching you Swift. If you are interested in learning Swift then I highly recommend checking out our Learn Swift track which will take you from novice to proficient in the fundamentals of Swift.

Each is designed by our faculty of tech professionals to guide even a coding beginner to becoming a job-ready software developer armed with a professional portfolio of real-world projects. Try one out today with our free seven-day trial, and see if software development is for you.