Core Concepts
Collections
Work with Swift arrays, dictionaries, and sets — powerful, type-safe collection types.
Swift Collections
Swift provides three primary collection types:
- Array: Ordered, indexed collection
- Dictionary: Key-value pairs
- Set: Unordered collection of unique values
All three are generic, value types (structs). When you assign them to a variable, you get a copy.
Value Semantics
Swift collections use value semantics — when you copy a collection, you get an independent copy. This is different from most languages where collections are reference types.
Higher-Order Functions
Swift arrays have powerful functional methods: map, filter, reduce, sorted, forEach, compactMap, flatMap
Example
swift
// Arrays
var fruits = ["Apple", "Banana", "Cherry"]
fruits.append("Date")
fruits.insert("Avocado", at: 0)
fruits.remove(at: 1)
print(fruits.count)
print(fruits.first ?? "empty")
print(fruits.last ?? "empty")
print(fruits.contains("Cherry"))
// Array operations
let numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
let sorted = numbers.sorted()
let unique = Set(numbers).sorted() // remove duplicates
let doubled = numbers.map { $0 * 2 }
let evens = numbers.filter { $0 % 2 == 0 }
let sum = numbers.reduce(0, +)
// Dictionaries
var person: [String: Any] = [
"name": "Alice",
"age": 30,
"city": "Paris"
]
person["email"] = "alice@example.com"
if let name = person["name"] as? String {
print("Name: \(name)")
}
// Iterating
for (key, value) in person {
print("\(key): \(value)")
}
// Sets
var colors: Set = ["red", "green", "blue"]
colors.insert("yellow")
colors.remove("red")
print(colors.contains("green")) // true
// Set operations
let setA: Set = [1, 2, 3, 4]
let setB: Set = [3, 4, 5, 6]
print(setA.union(setB)) // {1, 2, 3, 4, 5, 6}
print(setA.intersection(setB)) // {3, 4}
print(setA.subtracting(setB)) // {1, 2}Try it yourself — SWIFT