Skip to main content
  1. SwiftUI in 100 Days Notes/

Day 3 - Swift Complex Data Types: Arrays, Dictionaries, Sets, and Enums

In this section; we will examine complex data types such as Array, Dictionary, Set and Enum.

Swift Array #

Array is a data type, just like String, Int, Double. The purpose is to keep a lot of data organized and ordered in one place. The data types in an array are all the same. Arrays are created with square brackets ([) and each element is separated by commas (,). Let’s create Array as an example;

var beatles = ["John", "Paul", "George", "Ringo"]
let numbers = [4, 8, 15, 16, 23, 42]
var temperatures = [25.3, 28.2, 26.4]

When we want to read data from an Array, we can call the data with index, which is the sequence number of the data we want to read.

Array’s index number starts from 0. So the first element of the array has index number 0. **

print(beatles[0])      //OUTPUT: John
print(numbers[1])      //OUTPUT: 8
print(temperatures[2]) //OUTPUT: 26.4

Defining an Empty Array #

SSince Swift is a Type Safe language, it must always know what type of data an Array holds. If we create an Array with initial data, Swift can know what type it is. But if we create an empty Array and then fill it with data, we must specify the type of the Array at the creation stage. Determining the type of Array can be done in 2 ways.

Way 1

// Creates an empty String Array
var albums = Array<String>()

Way 2

// Creates an empty String Array
var albums = [String]()

Some Array Functions #

.append() #

You can use this function if a variable Array is defined. For example, beatles Array is defined as var so this function can be used, while numbers Array is defined as let so no new data can be added to it.

beatles.append("Allen")
beatles.append("Adrian")
beatles.append("Novall")
beatles.append("Vivian")

Also, whatever type the array was originally defined as (String, Double, Int), the data to be added later must also be of that type.

For example, the following code is incorrect because the temperatures Array is of type Double, so String data cannot be added.

//THIS CODE IS FAULTY.
temperatures.append("Chris")

.count() #

With the count() function, which we have already seen in Strings, we can find out how many items there are in an Array.

print(beatles.count) 
//OUTPUT: 4

.remove(at:) and .removeAll() #

With remove(at:) we can delete an Array item at a specific index.

We can also use removeAll() to delete all items in the Array.

var characters = ["Lana", "Pam", "Ray", "Sterling"]
print(characters.count) //OUTPUT: 4

characters.remove(at: 2)
print(characters.count) //OUTPUT: 3

characters.removeAll()
print(characters.count) //OUTPUT: 0

.contains() #

The contains() function checks if the item we are looking for exists in the Array. It returns true if it exists and false otherwise.

let bondMovies = ["Casino Royale", "Spectre", "No Time To Die"]
print(bondMovies.contains("Frozen")) 
//OUTPUT: false

.sorted() #

Returns the Array to which it is applied sorted in ascending order. The original array remains unchanged.

let cities = ["London", "Tokyo", "Rome", "Budapest"]
print(cities.sorted())
//OUTPUT: ["Budapest", "London", "Rome", "Tokyo"]

.reversed() #

We can invert an Array with the reversed() function.

let presidents = ["Bush", "Obama", "Trump", "Biden"]
let reversedPresidents = presidents.reversed()
print(reversedPresidents)
//OUTPUT: ReversedCollection<Array<String>>(_base: ["Bush", "Obama", "Trump", "Biden"])

Swift Dictionary #

We have already mentioned that when working with arrays, the data has to be in a certain order. This leads to the following problem: suppose we have a complex set of data and we save it in an Array. When we want to pull some data from this Array and use it, we absolutely need to know the index number of the data. But what if some data has been deleted and the index number we are looking for has changed? There’s the problem again.

To eliminate this problem in Array, the Dictionary type comes to our rescue. **In a Dictionary, the data is not kept in a specific order, it is kept as a Key-Value binary. In this way, we can access the data we want by giving the Key of the data we are looking for.

let employee2 = [
    "name": "Taylor Swift",
    "job": "Singer", 
    "location": "Nashville"
]

In the Dictionary above, name, job and location are referred to as key.

Taylor Swift , Singer and Nashville are value

When we want to read data from a Dictionary, we just need to give the key.

print(employee2["name"]) //OUTPUT: Optional("Taylor Swift")
print(employee2["job"]) //OUTPUT: Optional("Singer")
print(employee2["location"]) //OUTPUT: Optional("Nashville")

When we examine Swift’s output above, we see that it is marked as Optional. We will discuss this later, but the reason for this is that Swift wants to approach our code in a safe way. Because it may have misspelled the key or there may never have been such a key. For now, we will use the default keyword to avoid this error.

print(employee2["name", default: "Unknown"]) //OUTPUT: Taylor Swift
print(employee2["job", default: "Unknown"]) //OUTPUT: Singer
print(employee2["location", default: "Unknown"]) //OUTPUT: Nashville

In this way, we are saying to Swift: “Hey here is a default value, if the key I want is not in the dictionary, give me the default value.” In this way, Swift will not mark the output as optional since we know that it will definitely return a value.

Defining an Empty Dictionary #

As we did with Array before, we can define Dictionary as empty.

As seen in the example below, key is defined as String and value is defined as Int.

var heights = [String:Int]()
heights["Yao Ming"] = 229
heights["Shaquille O'Neal"] = 216
heights["LeBron James"] = 206

When you want to add data to any key, data is added if that key has not been used before. But if that key already exists, the value held by the key is modified.

The count() and removeAll() functions we see in Array can also be used in Dictionary.

Swift Set #

The property of sets is that the data is not kept ordered and there can be only 1 of each data.

Set expressions can be created as follows.

let people = Set(["Denzel Washington", 
				    "Tom Cruise", 
				    "Nicolas Cage", 
					"Samuel L Jackson",
					"Denzel Washington"])

If you notice in the example above, first an Array is created and then this Array is converted to a Set. Set will remove duplicate data from the given Array.

print(people)
//OUTPUT: ["Samuel L Jackson", "Denzel Washington", "Tom Cruise", "Nicolas Cage"]

When we examine the print(people) output, notice that the order has changed and Denzel Washington, which was written 2 times, is written 1 time.

Defining an Empty Set #

As we did with Array and Dictionary, an empty Set can be created as shown in the example below.

var people = Set<String>()
people.insert("Denzel Washington")
people.insert("Tom Cruise")
people.insert("Nicolas Cage")
people.insert("Samuel L Jackson")

The insert() function is used when you want to add new data to Sets. The append() function is not used in Sets, because Sets do not hold ordered data like Array.

The contains() function can check if the Set contains the data we are looking for.

The count function returns the number of data in the Set.

The sorted() function can return a sorted version of the Set.

Advantages of Set #

  1. Sometimes we may not need repeated data in the data we have. This is where Sets come to the rescue, and when creating a Set from an Array, it does not save the repeated data. So we can be sure that the data in Sets is unique.
  2. The data stored in Sets is unordered and optimized to be found quickly. This means that in a multi-element Set, we can use a function like contains() to quickly check if the data we want is contained in the Set.

Swift Enumeration #

Enum expressions are actually named values. But it is more efficient and safer than using String. Let’s say we want to pick a day of the weekday:

var selected = "Monday"

Then we will change this selection;

selected = "Tuesday"

Then we will change it once more;

selected = "Friday "

Notice that in the last change I accidentally wrote the day as Friday and left a space at the end. If I check the selected variable Friday (without a space) elsewhere in the program I will get an error. It will also cost more to check 2 String expressions.

This is where Enum expressions come into play. Let’s rewrite the days of the weekday;

enum Weekday {
    case monday
    case tuesday
    case wednesday
    case thursday
    case friday
}

Above we have defined 5 states of working days.

var day = Weekday.monday
day = Weekday.tuesday
day = Weekday.friday

I keep changing the day variable, but the possibility of mistyping has disappeared. Now there is no way I can accidentally type Friday (with spaces).

We can also define the Weekday enum as follows.

enum Weekday {
    case monday, tuesday, wednesday, thursday, friday
}

Another convenience when writing enum expressions is that the root enum expression may not be written after the first assignment.

var day = Weekday.monday
day = .tuesday
day = .friday

After the enum assignment with the day variable, there will be an enum of type Weekday, so there is no need to type Weekday each time.

You can also read this article in Turkish.
Bu yazıyı Türkçe olarak da okuyabilirsiniz.

This article contains the notes I took for myself from the articles found at SwiftUI Day 3. Please use the link to follow the original lesson.