Collections
## Learning Objectives
- Work with Arrays
- Use Sets for unique values
- Master Dictionaries
- Understand collection mutability
## Arrays
### Creating Arrays
```swift
// Empty array
let empty: [Int] = []
let empty2 = Array()
// With initial values
let numbers = [1, 2, 3, 4, 5]
let strings = ["one", "two", "three"]
// Repeated value
let zeros = [Int](repeating: 0, count: 5) // [0, 0, 0, 0, 0]
```
### Type Annotation
```swift
let ints: [Int] = [1, 2, 3]
let doubles: [Double] = [1.0, 2.0, 3.0]
let strings: [String] = ["a", "b", "c"]
```
### Array Type Shorthand
```swift
var names: [String] = ["Alice", "Bob"]
// names is Array
```
## Accessing Elements
### Index Access
```swift
let fruits = ["apple", "banana", "cherry"]
let first = fruits[0] // "apple"
let last = fruits[2] // "cherry"
// fruits[5] // Runtime error!
```
### First and Last
```swift
let first = fruits.first // Optional("apple")
let last = fruits.last // Optional("cherry")
if let first = fruits.first {
print(first)
}
```
### Check if Empty
```swift
let empty: [Int] = []
empty.isEmpty // true
empty.count // 0
let numbers = [1, 2, 3]
numbers.isEmpty // false
numbers.count // 3
```
## Modifying Arrays
### var Arrays
```swift
var array = [1, 2, 3]
// Add element
array.append(4) // [1, 2, 3, 4]
// Append contents of another array
array.append(contentsOf: [5, 6]) // [1, 2, 3, 4, 5, 6]
// Insert at index
array.insert(0, at: 0) // [0, 1, 2, 3, 4, 5, 6]
// Remove
array.remove(at: 0) // Returns 0, array is [1, 2, 3, 4, 5, 6]
array.removeFirst() // Returns 1, array is [2, 3, 4, 5, 6]
array.removeLast() // Returns 6, array is [2, 3, 4, 5]
// Remove all
array.removeAll()
```
### Update Elements
```swift
var scores = [90, 85, 88]
scores[0] = 95 // [95, 85, 88]
scores[1...2] = [100, 100] // [95, 100, 100]
```
## Array Iteration
### For-In Loop
```swift
let fruits = ["apple", "banana", "cherry"]
for fruit in fruits {
print(fruit)
}
// With index
for (index, fruit) in fruits.enumerated() {
print("\(index): \(fruit)")
}
```
## Array Methods
### Sorting
```swift
var numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort() // In-place: [1, 1, 2, 3, 4, 5, 6, 9]
let sorted = numbers.sorted() // Returns new array
// Custom sort
let sortedDesc = numbers.sorted(by: >) // Descending
```
### Reversing
```swift
let reversed = numbers.reversed() // ReversedCollection
let reversedArray = Array(numbers.reversed()) // [6, 2, 9, 5, 1, 4, 1, 3]
```
### Contains and Find
```swift
let numbers = [1, 2, 3, 4, 5]
numbers.contains(3) // true
numbers.contains { $0 > 3 } // true
if let index = numbers.firstIndex(of: 3) {
print("Found at \(index)")
}
if let first = numbers.first(where: { $0 > 3 }) {
print("First > 3 is \(first)") // 4
}
```
### Filtering
```swift
let numbers = [1, 2, 3, 4, 5, 6]
let evens = numbers.filter { $0 % 2 == 0 } // [2, 4, 6]
let greaterThan3 = numbers.filter { $0 > 3 } // [4, 5, 6]
```
### Mapping
```swift
let numbers = [1, 2, 3]
let doubled = numbers.map { $0 * 2 } // [2, 4, 6]
let strings = numbers.map { String($0) } // ["1", "2", "3"]
```
### Reducing
```swift
let numbers = [1, 2, 3, 4, 5]
let sum = numbers.reduce(0) { $0 + $1 } // 15
let product = numbers.reduce(1, *) // 120
```
## Sets
### Creating Sets
```swift
// Empty set
let empty: Set = Set()
let empty2 = Set()
// With values
var fruits: Set = ["apple", "banana", "cherry"]
let numbers: Set = [1, 2, 3, 4, 5]
```
### Key Properties
```swift
let colors = Set(["red", "green", "blue"])
colors.count // 3
colors.isEmpty // false
colors.first // Optional value (no order)
```
## Set Operations
### Insert and Remove
```swift
var fruits: Set = ["apple", "banana"]
fruits.insert("cherry") // ("cherry", true) if new
fruits.remove("apple") // Optional("apple") if existed
fruits.remove("grape") // nil (not in set)
// Check membership
if fruits.contains("banana") {
print("Has banana")
}
```
### Union
```swift
let setA: Set = [1, 2, 3]
let setB: Set = [3, 4, 5]
let union = setA.union(setB) // [1, 2, 3, 4, 5]
let unionA = setA | setB // [1, 2, 3, 4, 5]
```
### Intersection
```swift
let common = setA.intersection(setB) // [3]
let common2 = setA & setB // [3]
```
### Subtraction
```swift
let onlyA = setA.subtracting(setB) // [1, 2]
let onlyA2 = setA - setB // [1, 2]
```
### Symmetric Difference
```swift
let diff = setA.symmetricDifference(setB) // [1, 2, 4, 5]
let diff2 = setA ^ setB // [1, 2, 4, 5]
```
### Subset and Superset
```swift
let a: Set = [1, 2]
let b: Set = [1, 2, 3]
let c: Set = [1, 2, 3]
a.isSubset(of: b) // true
b.isSuperset(of: a) // true
b.isStrictSubset(of: c) // false
b.isStrictSuperset(of: a) // true
```
## Dictionaries
### Creating Dictionaries
```swift
// Empty dictionary
let empty: [String: Int] = [:]
let empty2 = Dictionary()
// With values
var ages = ["Alice": 30, "Bob": 25, "Charlie": 35]
```
### Dictionary Type Annotation
```swift
var names: [Int: String] = [
1: "One",
2: "Two",
3: "Three"
]
```
## Accessing Values
### Subscript Access
```swift
let ages = ["Alice": 30, "Bob": 25]
let age = ages["Alice"] // Optional(30)
let unknown = ages["Eve"] // nil
// Provide default
let name = ages["Alice", default: 0] // 30
let missing = ages["Eve", default: 0] // 0
```
### Key Existence
```swift
if ages["Alice"] != nil {
print("Alice exists")
}
// Alternative
if let aliceAge = ages["Alice"] {
print("Alice is \(aliceAge)")
}
```
## Modifying Dictionaries
### Add/Update
```swift
var ages = ["Alice": 30, "Bob": 25]
// Add new
ages["Charlie"] = 35
// Update existing
ages["Alice"] = 31
// Update with closure
ages.updateValue(40, forKey: "Bob") // Returns old value (25)
```
### Remove
```swift
var ages = ["Alice": 30, "Bob": 25, "Charlie": 35]
ages.removeValue(forKey: "Charlie") // Returns removed value
ages.removeValue(forKey: "Eve") // Returns nil
ages["Bob"] = nil // Also removes
ages.removeAll()
```
## Dictionary Iteration
### Dictionary For-In Loop
```swift
let ages = ["Alice": 30, "Bob": 25, "Charlie": 35]
for (name, age) in ages {
print("\(name): \(age)")
}
// Keys only
for name in ages.keys {
print(name)
}
// Values only
for age in ages.values {
print(age)
}
```
## Dictionary Methods
### Properties
```swift
let ages = ["Alice": 30, "Bob": 25]
ages.count // 2
ages.isEmpty // false
ages.keys // ["Alice", "Bob"]
ages.values // [30, 25]
```
### Dictionary Filtering
```swift
let ages = ["Alice": 30, "Bob": 25, "Charlie": 35, "Diana": 40]
let adults = ages.filter { $0.value >= 30 } // ["Alice": 30, "Charlie": 35, "Diana": 40]
```
### Dictionary Mapping
```swift
let ages = ["Alice": 30, "Bob": 25]
let descriptions = ages.mapValues { "\($0) years old" }
// ["Alice": "30 years old", "Bob": "25 years old"]
```
## Summary
- Arrays: ordered, indexed, allow duplicates
- Sets: unordered, unique values, mathematical operations
- Dictionaries: key-value pairs, fast lookup
- Use `var` for mutable collections
- Access with subscripts or methods
- Higher-order functions: map, filter, reduce
- `first`, `last` return optionals
- Use `isEmpty` before accessing
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →