Lesson 5 of 8
Collections & Closures
Learn , dictionaries and , and how to transform them with and map, filter and reduce, including the short $0 syntax.
var fruits = ["apple", "banana", "cherry"]
fruits.append("date")
fruits[0] // "apple"
fruits.count // 4
fruits.contains("banana") // true
var ages = ["Ada": 17, "Alan": 16]
ages["Grace"] = 17 // insert
let adaAge = ages["Ada"] // Int? — key might be missing!
let unique: Set = [1, 2, 2, 3] // {1, 2, 3}
// let makes collections deeply immutable:
let locked = [1, 2, 3]
// locked.append(4) // errorlet students = [
(name: "Ada", grade: 95),
(name: "Alan", grade: 88),
(name: "Grace", grade: 92),
]
// Closures, from verbose to idiomatic:
let names1 = students.map({ (s: (name: String, grade: Int)) -> String in
return s.name
})
let names2 = students.map { $0.name } // same thing
let honorRoll = students
.filter { $0.grade >= 90 }
.map { $0.name }
.sorted() // ["Ada", "Grace"]
let total = students.reduce(0) { $0 + $1.grade }
let best = students.max { $0.grade < $1.grade }
// sorted with a custom order:
let byGrade = students.sorted { $0.grade > $1.grade }Finished reading?Mark it done to track your progress.
Tip: use the ← and → keys to move between lessons.