The Ultimate Guide to Swift Arrays, Sets, and Dictionaries

The Swift Programming Language comes with 3 primary Collection Types to use out of the box: Arrays, Sets & Dictionaries.

Each serves a specific purpose, let’s explore and see how to use them effectively.

The most common one that you will use on a daily basis is Array


Understanding Swift Collection Types

Array

Arrays are an ordered collection of items of the same type.

Arrays are index based, starting from zero.

Initialization

// Empty array
var numbers: [Int] = []

// Array with values
var fruits: [String] = ["Apple", "Banana", "Cherry"]

Insertion & Deletion

// Append an element
fruits.append("Mango")

// Insert at a specific index
fruits.insert("Orange", at: 1)

// Remove an element
fruits.remove(at: 2)

// Remove last element
fruits.removeLast()

Accessing Elements

let firstFruit = fruits[0] // "Apple"

Set

A Set is an unordered collection of unique items, hence no duplicates.

Sets are more performant than arrays.

Initialization

// Empty set
var uniqueNumbers: Set<Int> = []

// Set with values
var colors: Set<String> = ["Red", "Green", "Blue"]

Insertion & Deletion

// Insert an element
colors.insert("Yellow")

// Remove an element
colors.remove("Green")

Checking membership

if colors.contains("Blue") {
    print("Blue is in the set")
}

Dictionary

A Dictionary it’s an unordered collection of key-value pairs, where keys must be unique.

Initialization

// Empty dictionary
var studentGrades: [String: Int] = [:]

// Dictionary with values
var employeeSalaries: [String: Int] = [
    "Alice": 50000,
    "Bob": 60000
]

Insertion & Deletion

// Add or update a value
employeeSalaries["Charlie"] = 55000

// Remove a key-value pair
employeeSalaries.removeValue(forKey: "Bob")

Accessing Elements

if let salary = employeeSalaries["Alice"] {
    print("Alice's salary is \\(salary)")
}

Comparison between Array, Set & Dictionaries

FeatureArraySetDictionary
OrderYesNoNo
DuplicatesYesNoKeys: No, Values: Yes
IndexingYesNoNo
Fast LookupNoYesYes
  • Use Arrays when order matters or when duplicate values are needed. They are ideal for sequential storage and easy access using an index, making them suitable for lists, stacks, or ordered datasets.
  • Use Sets for unique values and fast membership checks. Sets perform exceptionally well when checking for existence or ensuring that no duplicates exist in your dataset, such as in tag lists or unique user IDs.
  • Use Dictionaries for key-value relationships and quick lookups. When you need to map keys to values, like storing user profiles or configurations, dictionaries provide efficient access and modification of data.

I hope you learned something new today!

Thanks for reading!


Browse categories

TOC