Lesson 22Collections

Array Operations

Powerful Array Methods

Swift arrays come with many built-in methods for transforming, filtering, and processing data. These are essential tools for every Swift developer!

The Big Three

map

Transform each element

[1,2,3].map { $0 * 2 }

→ [2, 4, 6]

filter

Keep matching elements

[1,2,3].filter { $0 > 1 }

→ [2, 3]

reduce

Combine to single value

[1,2,3].reduce(0, +)

→ 6

Sorting & Ordering

.sorted()

Returns new sorted array

.sort()

Sorts in place (mutates)

.reversed()

Reverses order

.shuffled()

Random order

Finding Elements

.first { condition }

First matching element

.firstIndex(of:)

Index of element

.contains()

Check if exists

.allSatisfy { }

All match condition?

What is $0?

$0 is a shorthand for the first argument in a closure. $1 is the second, etc.

.map { $0 * 2 } is the same as .map { num in num * 2 }

main.swift
// Looping through arrays
let fruits = ["Apple", "Banana", "Orange"]

// Simple for-in loop
for fruit in fruits {
    print(fruit)
}

// With index using enumerated()
for (index, fruit) in fruits.enumerated() {
    print("\(index): \(fruit)")
}

// Transforming with map
let numbers = [1, 2, 3, 4, 5]
let doubled = numbers.map { $0 * 2 }
print(doubled)  // [2, 4, 6, 8, 10]

// Filtering with filter
let evenNumbers = numbers.filter { $0 % 2 == 0 }
print(evenNumbers)  // [2, 4]

// Reducing to single value
let sum = numbers.reduce(0) { $0 + $1 }
print("Sum: \(sum)")  // 15

// Sorting
var scores = [85, 92, 78, 95, 88]
let sorted = scores.sorted()           // Ascending
let descending = scores.sorted(by: >)  // Descending
print(sorted)

// Sort in place
scores.sort()
print(scores)

// Reversing
let reversed = fruits.reversed()
print(Array(reversed))

// Combining arrays
let moreNumbers = [6, 7, 8]
let combined = numbers + moreNumbers
print(combined)  // [1, 2, 3, 4, 5, 6, 7, 8]

// Array slicing
let slice = numbers[1...3]  // Elements 1, 2, 3
print(Array(slice))  // [2, 3, 4]

// First/Last with condition
let firstEven = numbers.first { $0 % 2 == 0 }
print(firstEven ?? "None")  // 2

// Checking conditions
let allPositive = numbers.allSatisfy { $0 > 0 }
print("All positive: \(allPositive)")  // true

// Compact map - removes nils
let strings = ["1", "2", "three", "4"]
let validNumbers = strings.compactMap { Int($0) }
print(validNumbers)  // [1, 2, 4]

Try It Yourself!

Given an array of test scores, use filter to get passing scores (>60), map to add bonus points (+5), and reduce to calculate the average!