Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a closure that adds two numbers.
Swift
let add = { (a: Int, b: Int) -> Int in return a [1] b } Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-' instead of '+' will subtract instead of add.
✗ Incorrect
The closure adds two integers using the + operator.
2fill in blank
mediumComplete the code to call the closure with arguments 3 and 5.
Swift
let result = add([1], 5)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing 4 or 6 instead of 3 will change the result.
✗ Incorrect
The closure is called with 3 and 5 as arguments, so the first argument is 3.
3fill in blank
hardFix the error in the closure syntax to correctly multiply two numbers.
Swift
let multiply = { (a: Int, b: Int) -> Int [1] a * b } Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'return' or 'func' instead of 'in' causes syntax errors.
✗ Incorrect
The keyword 'in' separates the closure parameters and return type from the body.
4fill in blank
hardFill both blanks to create a closure that returns the square of a number.
Swift
let square = { (num: Int) [1] num [2] num } Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '**' for exponentiation is not valid in Swift.
✗ Incorrect
The closure uses 'in' to separate parameters from the body and '*' to multiply the number by itself.
5fill in blank
hardFill all three blanks to create a closure that filters even numbers from an array.
Swift
let evens = numbers.filter { [1] in [2] % 2 [3] 0 } Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!=' instead of '==' will filter odd numbers instead.
✗ Incorrect
The closure takes 'num' as input, then checks if 'num % 2 == 0' to filter even numbers.