Skip to content
Educora
Intermediate18 min5 / 14

Collections: arrays, dictionaries, sets

Store many values in arrays, dictionaries and sets, change them and process them in one line with `map`, `filter` and `reduce`.

Check yourself
In this lesson you will learn
  • Create an array, access elements by index, add and remove them
  • Work with dictionaries and sets and choose which collection fits a task
  • Transform collections with map, filter and reduce

In a music app a playlist keeps songs in a certain order, a phone book finds a number by a name, and a “liked” list cannot contain the same photo twice. For these three situations Swift has three collections: the array (Array), the dictionary (Dictionary) and the set (Set).

Arrays

An array is an ordered list of values of the same type, written in square brackets. Every element has an index, and counting starts at 0: the first element is fruits[0]. An array's type is written like [String] or [Int]. An array declared with var can be changed; a let array cannot.

Swift
var fruits = ["apple", "banana", "cherry"]
print(fruits)
print(fruits[0])
print(fruits.count)

fruits.append("pear")
fruits.insert("kiwi", at: 1)
print(fruits)

fruits.remove(at: 2)
print(fruits)
print(fruits.contains("pear"))
print(fruits.first ?? "empty")
Expected output
["apple", "banana", "cherry"]
apple
3
["apple", "kiwi", "banana", "cherry", "pear"]
["apple", "kiwi", "cherry", "pear"]
true
apple

first and last return optionals, because an array can be empty. To loop over an array use for-in, and if you need both the index and the value, use enumerated(). sorted() returns a new sorted array, and max() and min() return the largest and smallest element (as optionals).

Swift
let scores = [85, 92, 78]
for (index, score) in scores.enumerated() {
    print("\(index + 1). \(score)")
}
print(scores.sorted())
print(scores.max() ?? 0)

let empty: [Int] = []
print(empty.isEmpty)
Expected output
1. 85
2. 92
3. 78
[78, 85, 92]
92
true

Dictionaries

A dictionary stores key: value pairs and finds a value by its key, not by an index. Its type is written like [String: String]. A value read by a key is always optional, because the key might not exist — this is where ?? is very useful. Assigning nil to a key removes the pair.

Swift
var capitals = ["Azerbaijan": "Baku", "Georgia": "Tbilisi"]
capitals["Japan"] = "Tokyo"

print(capitals["Azerbaijan"] ?? "unknown")
print(capitals["France"] ?? "unknown")
print(capitals["Japan"])

capitals["Georgia"] = nil
print(capitals.count)

for country in capitals.keys.sorted() {
    print("\(country) -> \(capitals[country] ?? "")")
}
Expected output
Baku
unknown
Optional("Tokyo")
2
Azerbaijan -> Baku
Japan -> Tokyo

One of the most useful jobs for a dictionary is counting. A class voted for its favourite animal — how many votes did each animal get?

Swift
let votes = ["cat", "dog", "cat", "fish", "cat", "dog"]
var counts: [String: Int] = [:]

for vote in votes {
    counts[vote, default: 0] += 1
}

for animal in counts.keys.sorted() {
    print(animal, counts[animal, default: 0])
}
Expected output
cat 3
dog 2
fish 1

Sets

A set (Set) is a collection of unique values with no order. If you add the same value twice, it is stored only once. Sets check very quickly whether an element is present and support intersection (intersection) and union (union), just like in mathematics.

Swift
var visited: Set = ["Baku", "Ganja", "Baku", "Shaki"]
print(visited.count)

visited.insert("Lankaran")
print(visited.contains("Ganja"))

let friendVisited: Set = ["Baku", "Quba"]
print(visited.intersection(friendVisited).sorted())
print(visited.union(friendVisited).sorted())
Expected output
3
true
["Baku"]
["Baku", "Ganja", "Lankaran", "Quba", "Shaki"]
CollectionOrderDuplicatesWhen to choose it
Array [T]yesallowedwhen order matters: a playlist, a queue
Dictionary [K: V]nokeys are uniquelooking up by key: contacts, prices
Set Set<T>nonot alloweduniqueness and fast checks: tags, visited cities

`map`, `filter` and `reduce`

There are three powerful methods for processing collections without writing a loop. map transforms every element into a new array, filter keeps only the elements that match a condition, and reduce combines all elements into one value. The code in curly braces is a closure, and $0 is the current element — you will study closures in detail in the next lesson.

Swift
let prices = [4, 12, 7, 20]

let doubled = prices.map { $0 * 2 }
let cheap = prices.filter { $0 < 10 }
let total = prices.reduce(0, +)

print(doubled)
print(cheap)
print(total)
print(prices.filter { $0 >= 10 }.reduce(0, +))

let names = ["aysel", "murad"]
print(names.map { $0.uppercased() })
Expected output
[8, 24, 14, 40]
[4, 7]
43
32
["AYSEL", "MURAD"]

Key points

  • An array is ordered and its indices start at 0; going out of range crashes the program.
  • A dictionary finds values by key and returns an optional; assigning nil removes a pair.
  • Dictionaries and sets have no order — use sorted() for a stable result.
  • A set keeps unique values and supports intersection and union.
  • map transforms, filter selects, reduce combines.

Check yourself

10 questions. Every correct answer earns XP.

1 / 10
If let a = [10, 20, 30], what is a[1]?