🐦 Swift
Closures
Closures are self-contained blocks of functionality that can be passed around and used in your code. They're similar to functions but written in a more compact syntax. Closures are used everywhere in Swift — in completion handlers, array transformations, and UI callbacks.
Closure Syntax
A closure captures and references variables from the surrounding context. Here's how the syntax evolves from full form to shorthand:
Editor
Swift
Output
Try it
Modify the filter to keep only even numbers ($0 % 2 == 0) instead of numbers greater than 4.
Shorthand Arguments
// $0 refers to the first argument
// $1 refers to the second argument
// $2, $3... and so on
let words = ["hello", "world"]
// Full form
let upper1 = words.map { (word: String) -> String in
return word.uppercased()
}
// Short form with $0
let upper2 = words.map { $0.uppercased() }
// Trailing closure syntax
let upper3 = words.map {
$0.uppercased()
}
// All produce: ["HELLO", "WORLD"]
Map, Filter, Reduce
- → map — Transforms every element in a collection and returns a new array.
- → filter — Tests each element and keeps only those that pass the test.
- → reduce — Combines all elements into a single value using an accumulator.
- → forEach — Iterates over a collection without producing a result.
Quiz
What does $0 refer to in a closure?
Challenge
Use map to transform an array of strings to uppercase. Try using both the full closure syntax and the $0 shorthand.