Closure Basics
Part of the Logic & Flow section of Coddy's Swift journey — lesson 38 of 56.
A closure is a self-contained block of code you can pass around and call later. The full syntax spells out parameter and return types:
let double = { (n: Int) -> Int in
return n * 2
}
print(double(5)) // 10Swift can infer the types when the context is clear, so you rarely write the long form. Inside map, filter, etc., the shorter shorthand is the norm:
let nums = [1, 2, 3, 4]
let doubled = nums.map { n in n * 2 }
let alsoDoubled = nums.map { $0 * 2 } // shortest, $0 is the first argClosures are values, you can store them in variables, return them from functions, and pass them as arguments. That's the whole reason map works.
Challenge
EasyRead two lines of input:
- An integer
x - A comma-separated list of integers
Define three closures, each (Int) -> Int:
addXaddsxto its argumentsquarereturns the argument squarednegatereturns the argument negated
Apply each closure to every element of the list using map. Print three lines, one per closure, with the results joined by ,:
addX: ...
square: ...
negate: ...For input 10 on line 1 and 1,2,3 on line 2, the output is:
addX: 11,12,13
square: 1,4,9
negate: -1,-2,-3Cheat sheet
A closure is a self-contained block of code that can be stored and passed around. Full syntax:
let double = { (n: Int) -> Int in
return n * 2
}Closures can be stored in variables and passed as arguments (e.g. to map). Swift infers types in context, enabling shorthand:
let nums = [1, 2, 3, 4]
let doubled = nums.map { n in n * 2 }
let alsoDoubled = nums.map { $0 * 2 } // $0 is the first argumentTry it yourself
let x = Int(readLine()!)!
let nums = readLine()!.components(separatedBy: ",").map { Int($0)! }
// TODO: define three (Int) -> Int closures and map nums through each
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Count and IndicesCase and TrimSearching in StringsSplitting and JoiningReplacing SubstringsRecap - Username Check