Arrays

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

In the last demo, you learned about using strings and created a personalized greeting message by concatenating multiple strings. You learned about string interpolation using \(). You also improved the calculator to print user-friendly messages on the console with information about each math operation and the result. You saw the difference in precision between Float and Double.

In this instruction, you’ll write Swift code that performs a basic task, generating the first few numbers in the Fibonacci sequence.

This mathematical sequence is used in some computer techniques like searching, data structures, and distributed systems. Big words … I know. :]

But what’s interesting is that this sequence exists in nature. It’s fascinating to see that different plants and flowers have this sequence as part of their shape.

The sequence looks like this:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...

Starting with 0 and 1, each digit is the sum of the two numbers before it. So the 10th number, for example (55), is the sum of the 9th digit (34) and the 8th digit (21).

It’s easy to understand. But this sequence is an interesting topic in programming for the simple reason that calculating any number of the sequence requires knowing the ones before it, and knowing those requires knowing the ones before them, and so on until you reach the beginning with 0 and 1.

So before getting into writing code, you need to understand how Swift handles sequences.

A sequence of elements can be presented in Swift as an array. An array of Int is represented with the data type [Int]:

var intArray: [Int] = [0, 1, 2, 3, 4, 5]

Arrays are an ordered sequence of elements; you can access any specific element from the array by the index of that element in the array:

let firstElement = intArray[0]
let thirdElement = intArray[2]

An array always starts from the index 0. This is very important to remember; otherwise, if you access the first with 1, you end up picking the wrong item. An array continues to an index that is one less than the total number of elements in the array.

You also need to be careful when you work with arrays that you don’t access elements outside the range of indexes:

let outOfBounds = intArray[10]

Accessing an element outside the boundaries of an array causes your app to crash. It’ll abruptly close, and the user’s session will be lost. You can imagine how frustrating this can be for a user. Don’t worry about this yet; later, you’ll learn how to check an array’s boundaries.

You can add more elements to an array with append:

intArray.append(6)
intArray.append(7)

append adds the provided element to the end of the array.

An important thing to know about arrays is that all the elements stored inside them must be the same type you specified when you created the array variable with the square brackets []. If you try to append an element of a different type in your intArray variable, Xcode complains:

let exampleFloat: Float = 8.0
intArray.append(exampleFloat) // <-- This line will give an error

The second line above gives you an error, and Xcode won’t allow you to execute any code. Xcode knows that the elements stored in intArray are all of type Int, while the element you’re trying to add to the array is Float.

You can create an array of Float or Double or even String like this:

var floatArray: [Float] = [1.0, 2.0, 3.0]
var doubleArray = [1.0, 2.0, 3.0]
var stringArray = ["First String", "Second String", "Third String"]

Swift can also automatically understand the type of the elements in the array from the initial values you use (aka type inference). Notice that if you want Float, you have to note that explicitly; otherwise, it’ll be inferred as Double.

In the next demo, you’ll start writing code to calculate the first few digits in the Fibonacci sequence and store them in an array. You’ll see firsthand after you write the code what improvements you need to make the code more organized and what additional programming concepts you need to learn in Swift.

See forum comments
Download course materials from Github
Previous: Strings Demo Next: Arrays Demo