You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Swift provides three primary collection types: Array, Set, and Dictionary. All three are generic, type-safe, and implemented as value types with copy-on-write optimisation.
An array is an ordered collection of elements of the same type:
// Creating arrays
var fruits: [String] = ["Apple", "Banana", "Cherry"]
var numbers = [1, 2, 3, 4, 5] // inferred as [Int]
var empty: [Double] = []
var repeated = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0]
// Accessing
let first = fruits[0] // "Apple"
let last = fruits.last // Optional("Cherry")
let count = fruits.count // 3
let isEmpty = fruits.isEmpty // false
// Modifying
fruits.append("Date") // ["Apple", "Banana", "Cherry", "Date"]
fruits.insert("Elderberry", at: 1)
fruits.remove(at: 0)
fruits[0] = "Blueberry"
// Safe access with bounds checking
if let item = fruits.first {
print("First fruit: \(item)")
}
for fruit in fruits {
print(fruit)
}
for (index, fruit) in fruits.enumerated() {
print("\(index): \(fruit)")
}
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let doubled = numbers.map { $0 * 2 }
// [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
let evens = numbers.filter { $0 % 2 == 0 }
// [2, 4, 6, 8, 10]
let sum = numbers.reduce(0, +)
// 55
let sorted = numbers.sorted(by: >)
// [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
let compacted: [Int] = [1, nil, 3, nil, 5].compactMap { $0 }
// [1, 3, 5]
A set is an unordered collection of unique elements:
var colours: Set<String> = ["Red", "Green", "Blue"]
var primes: Set = [2, 3, 5, 7, 11] // inferred as Set<Int>
let a: Set = [1, 2, 3, 4, 5]
let b: Set = [3, 4, 5, 6, 7]
a.union(b) // {1, 2, 3, 4, 5, 6, 7}
a.intersection(b) // {3, 4, 5}
a.subtracting(b) // {1, 2}
a.symmetricDifference(b) // {1, 2, 6, 7}
colours.contains("Red") // true
colours.insert("Yellow") // (inserted: true, memberAfterInsert: "Yellow")
colours.remove("Green") // Optional("Green")
let small: Set = [1, 2]
let large: Set = [1, 2, 3, 4]
small.isSubset(of: large) // true
large.isSuperset(of: small) // true
A dictionary is an unordered collection of key-value pairs:
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.