100 Days of iOS | Day 002 | arrays, dictionaries, sets, and enums

Rycco Atika
5 min readJul 19, 2024

--

Photo by Raymond Rasmusson on Unsplash

Welcome to Day 2 of my “100 Days of iOS Development Journey.” Yesterday, we kicked off this series with a deep dive into the basics of Swift, exploring variables, strings, integers, and more. Today, we’re going to build on that foundation by exploring some of Swift’s powerful data structures: arrays, dictionaries, sets, and enums.

As an Android developer, I’m accustomed to Java and Kotlin’s data structures, so I’m eager to compare them with what Swift offers. Understanding these fundamental data structures is crucial for any developer, as they form the backbone of most programming tasks. In today’s article, we’ll break down each of these structures, examine their unique features, and see how they can be effectively utilized in Swift.

Table of Contents

Arrays

Arrays are collections of values that are stored as a single value.

let john = "John Lennon"
let paul = "Paul McCartney"
let george = "George Harrison"
let anotherBeatles = [john, paul, george, "Ringo Starr"]

You can read values from an array by writing a number inside brackets. Array positions count from 0, so if you want to read “Paul McCartney” you would write this:

beatles[1]

Sets

Sets are collections of values just like arrays, except they have two differences:

  1. Items aren’t stored in any order; they are stored in what is effectively a random order.
  2. No item can appear twice in a set; all items must be unique.
let colors = Set(["red", "green", "blue", "yellow", "blue"])

The final colors set will still only include red, green, yellow, and blue once.

Tuples

Tuples allow you to store several values together in a single value. That might sound like arrays, but tuples are different:

  1. You can’t add or remove items from a tuple; they are fixed in size.
  2. You can’t change the type of items in a tuple; they always have the same types they were created with.
  3. You can access items in a tuple using numerical positions or by naming them, but Swift won’t let you read numbers or names that don’t exist.
var name = (first: "Taylor", last: "Swift")
name.0 // Taylor
name.first // Taylor
name.last // Swift

You can change the values inside a tuple after you create it, but not the types of values. So, if you tried to change name to be (first: "Justin", age: 25) you would get an error.

Arrays vs Sets vs Tuples

Arrays, sets, and tuples seem similar but they have distinct uses

If you need a specific, fixed collection of related values where each item has a precise position or name, you should use a tuple:

let address = (house: 555, street: "Taylor Swift Avenue", city: "Nashville")

If you need a collection of values that must be unique or you need to be able to check whether a specific item is in there extremely quickly, you should use a set:

letset = Set(["aardvark", "astronaut", "azalea"])

If you need a collection of values that can contain duplicates or the order of your items matters, you should use an array:

let pythons = ["Eric", "Graham", "John", "Michael", "Terry", "Terry"]

Dictionaries

Dictionaries are collections of values just like arrays, but rather than storing things with an integer position you can access them using anything you want.

let heights = [
"Taylor Swift": 1.78,
"Ed Sheeran": 1.73
]

heights["Taylor Swift"] // 1.78

Dictionary Default Value

If you try to read a value from a dictionary using a key that doesn’t exist, Swift will send you back nil – nothing at all

let heights = [
"Taylor Swift": 1.78,
"Ed Sheeran": 1.73
]

heights["Taylor Swift"] // 1.78
heights["Shawn Mendes"] // nil
heights["Shawn Mendes", default: 0.0] // 0.0

Creating Empty Collections

If you want to create an empty collection just write its type followed by opening and closing parentheses.

var teams = [String: String]()

teams["Paul"] = "Red"

Similarly, you can create an empty array to store integers like this:

var results = [Int]()

The exception is creating an empty set, which is done differently:

var words = Set<String>()
var numbers = Set<Int>()

This is because Swift has special syntax only for dictionaries and arrays; other types must use angle bracket syntax like sets.

If you wanted, you could create arrays and dictionaries with similar syntax:

var scores = Dictionary<String, Int>()
var results = Array<Int>()

Enumerations

Enumerations — usually called just enums — are a way of defining groups of related values in a way that makes them easier to use.

enum Result {
case success
case failure
}

let result = Result.success

Enum Associated Values

As well as storing a simple value, enums can also store associated values attached to each case. This lets you attach additional information to your enums so they can represent more nuanced data.

enum Activity {
case bored
case running(destination: String)
case talking(topic: String)
case singing(volume: Int)
}

let talking = Activity.talking(topic: "football")

Enum Raw Values

Sometimes you need to be able to assign values to enums so they have meaning. This lets you create them dynamically and use them in different ways.

enum Planet: Int {
case mercury
case venus
case earth
case mars
}

let mercury = Planet(rawValue: 0)
let earth = Planet(rawValue: 2)

If you want, you can assign one or more cases a specific value, and Swift will generate the rest. It’s not very natural for us to think of Earth as the second planet so you could write this:

Summary

In today’s exploration of Swift’s data structures, we dove into arrays, sets, tuples, dictionaries, and enums. Here’s a quick comparison:

  • Arrays: Similar to Kotlin listOf(...), arrays in Swift are ordered collections of values. They can be accessed using indices, just like in Kotlin.
  • Sets: These are collections of unique values in no particular order, similar to sets in Kotlin setOf(...). They are useful when you need to ensure all elements are unique.
  • Tuples: Kotlin does not have built-in support for tuples like Swift, but I think you can achieve similar functionality using Pair / Triple / Data Class.
  • Dictionaries: These are collections that map keys to values, akin to Kotlin’s mapOf. They allow for quick lookup based on a key.
  • Enums: Swift enums are powerful and versatile, and Kotlin enums are also as powerful as Swift.

References

--

--