Swift’s Collections: The Collected Works

Collections are for storing values. Which to use and when are essential for your development as a programmer

Image for post
Image for post
Photo by Karen Vardazaryan on Unsplash

Difficulty: Beginner | Easy | Normal | Challenging

Collection types allow you to store values, and you might think of this as a way to group those values. You will need to think about whether you want to order your values, and how you want to access them when they have been stored.

Read on for the details…(!)

Prerequisites:

  • Be able to produce a “Hello, World!” iOS application (guide HERE)

Terminology

Array: An ordered series of objects which are the same type

Collection: A sequence of elements that can be traversed (as many times as you want) and can be accessed by an indexed subscript

Data Type: A representation of the type of data that can be processed, for example Integer or String

The Collection Types in Swift

The Swift language has three Collection types available in Swift, all of which store values and are useful for developers to know about. Here is the shortened version for your quick reference:

Array : An ordered series of objects which are of the same type. This can be an array of Integers, Strings or any different data type in Swift

Dictionary: The association between keys and values (where all the keys are of the same type, and all values are of the same type)

Set: An unordered collection of values (where all the values are of the same type)

Arrays

Arrays in Swift are Zero-indexed which means we can store Characters

Image for post
Image for post

These elements can then be accessed through subscripting

arr[0] // returns "a"
arr[1] // returns "b"
arr[2] // returns "c"
arr[3] // returns "d"

meaning that the following equality statements are true

arr[0] == "a" // true
arr[1] == "b" // true
arr[2] == "c" // true
arr[3] == "d" // true

Arrays can also be joined together, which is often known as concatenation.

When we join two arrays, that is in the diagram below “a”,”b”,”c” and “d” added to “e”,”f”,”g” and “h”.

Image for post
Image for post

Since we add the second array to the first, you are left with the following new array

Image for post
Image for post

Appending to Arrays basically means adding elements to the end of an existing Array.

This is shown in the diagram below to show “e” appended on the end of an array containing “a”,”b”,”c” and “d”.

Image for post
Image for post

If we take this updated array “a”,”b”,”c”,“d”,”e” and change the second element to “z” (if the element is called arr we perform arr[2] = “z”) resulting in:

Image for post
Image for post

An alternative is to use Swift’s insert(:atIndex:) that allows us to insert an item at a particular index.

If we take our ongoing array (that now contains the elements “a”,”b”,”z”,“d”,”e”) and if we insert the element “y” at index 1.

The process is shown in a rather larger diagram below:

Image for post
Image for post

Similarly we can use Swift’s removeAtIndex(:) that allows us to remove an item at a particular index.

Image for post
Image for post

Moving through Arrays

This is possible by using the for in syntax in Swift (assuming the Array is named as arr).

for item in arr {
print (item) // in this example print the element
}

We can also enumerate over elements in Swift, giving us access to the index.

for (index,item) in arr.enumarate() {
print (index, item) // e.g. print the index and the element
}

There are also some things around ArraySlices, but I’ve left these for a separate article (HERE)

So we can set up an Array

var arr = [“a”,”b”,”c”,”d”]

The array operations are

Image for post
Image for post

Arrays are particularly great because they are ordered, so are a great way to present sorted data. Smashing!

Dictionaries

Dictionaries are known as HashMaps in other languages, and are a data structure that maps keys to values. They are often used for high-performance computing applications like caches and databases.

It is important to remember that, unlike Arrays, they are unordered (so when you read out this collection it will have an order but it may not be the same each time you run a program).

Dictionaries are extremely efficient in their lookup operation, and are unordered so we can obtain a value in constant time — just like flicking through a physical dictionary it doesn’t matter where the value lies in the structure it always takes the same time to access.

Initialising a Dictionary

var myDictionary = [Int: Int]()

The pictorial representation of a dictionary

The following is a representation of a dictionary with three elements as key-value pairs.

Image for post
Image for post

The three key-value pairs represented here (if we call the dictionary myDictionary) are myDictionary[4] = 11, myDictionary[8] = 7 and myDictionary[5] = 1.

Which enables us to use the following operations:

Image for post
Image for post

There is a full guide for the dictionary in Swift (The link is right here)

Sets

A set is an unordered collection, but it is only possible to have a single

Initialising a Set

var stringSet = Set<String>()

A set with a,b,c,d,e would look something like the following diagram:

Image for post
Image for post

We can then perform set operations on the structure

Image for post
Image for post

Conclusion:

If you’re storing data you probably need to use a collection. They are great to iterate over, and if you care about order you probably use an array. If you don’t care about the order and want speed of access, a dictionary is probably the way to go. If you want a data structure that supports set operations (and only a single instance of a value) choose a set.

In any case, over your programming journey you are likely to encounter these structures time and time again. Probably best to get used to them!

Extend your knowledge

  • If you are interested in Contiguous and non-contriguous arrays there is a full guide (HERE)
  • You can read about ArraySlices (HERE)
  • The full articles on Arrays, Dictionaries and Sets are available for you have a more in-depth look at

The Twitter contact:

Any questions? You can get in touch with me HERE

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store