Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to call the function with a closure that prints "Hello".
Swift
func greet(action: () -> Void) {
action()
}
greet [1] {
print("Hello")
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Including the closure type in the call instead of just parentheses.
Omitting parentheses entirely when no parameters are passed.
✗ Incorrect
The function greet is called with a trailing closure, so just empty parentheses () are needed before the closure block.
2fill in blank
mediumComplete the function parameter to accept a closure that takes an Int and returns an Int.
Swift
func modify(number: Int, with closure: [1]) -> Int { return closure(number) }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a closure type that returns Void instead of Int.
Using a closure type with no parameters.
✗ Incorrect
The closure parameter must take an Int and return an Int, so the type is (Int) -> Int.
3fill in blank
hardFix the error in the closure parameter type to accept a closure that takes two Ints and returns Bool.
Swift
func compare(a: Int, b: Int, using predicate: [1]) -> Bool { return predicate(a, b) }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a closure type with only one parameter.
Using a closure type with wrong parameter or return types.
✗ Incorrect
The closure must take two Int parameters and return a Bool, so the type is (Int, Int) -> Bool.
4fill in blank
hardFill both blanks to create a function that accepts a closure with no parameters and returns a String, then call it.
Swift
func fetchMessage(completion: [1]) { let message = completion() print(message) } fetchMessage [2] { return "Done" }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using closure types that return Void instead of String.
Omitting parentheses when calling the function.
✗ Incorrect
The function parameter is a closure with no parameters returning String, so () -> String. The call uses empty parentheses () before the closure.
5fill in blank
hardComplete the code to define and call a function that accepts a closure taking a String and returning an Int, then prints the result.
Swift
func process(text: String, with closure: [1]) { let length = closure(text) print("Length: \(length)") } process(text: "Swift") { text in return text.count }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting braces around the closure body.
Forgetting the 'in' keyword in the closure syntax.
✗ Incorrect
The closure type is (String) -> Int. The closure syntax uses braces { } and the keyword in to separate parameters from the body.