Complete the code to declare a closure that adds two numbers.
let add: (Int, Int) -> Int = [1] { $0 + $1 }
The correct syntax to declare a closure in Swift uses curly braces { }. So { $0 + $1 } defines the closure body.
Complete the code to assign a closure to a variable and call it.
var multiply = [1] (Int, Int) -> Int = { $0 * $1 } let result = multiply(3, 4)
Use let to declare a constant closure. Here, multiply is assigned a closure that multiplies two numbers.
Fix the error in the closure capturing a variable.
func makeIncrementer(forIncrement amount: Int) -> () -> Int {
var total = 0
let incrementer: () -> Int = {
total [1]= amount
return total
}
return incrementer
}The closure should add amount to total each time it is called, so += is the correct operator.
Fill both blanks to create a closure that captures and modifies a variable.
func makeCounter() -> () -> Int {
var count = 0
return {
count [1]= 1
return count [2] 0
}
}The closure increments count by 1 using += and returns whether count is greater than 0 using >.
Fill all three blanks to create a closure that captures a string and returns its length if longer than 3.
func makeStringChecker(_ text: String) -> () -> Int? {
return {
let length = text.[1]
if length [2] 3 {
return length
} else {
return [3]
}
}
}The closure gets the string length using count, checks if it is greater than 3, and returns nil if not.