Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to call the function with a trailing closure.
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
Omitting the parentheses when the function requires them.
Trying to put the closure inside the parentheses.
✗ Incorrect
The function greet is called with an empty parameter list followed by a trailing closure in braces.
2fill in blank
mediumComplete the code to use trailing closure syntax with a function that takes one closure parameter.
Swift
func perform(task: () -> Void) {
task()
}
perform[1] {
print("Task done")
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to name the closure parameter in the call.
Omitting the parentheses entirely.
✗ Incorrect
The function perform is called with empty parentheses followed by the trailing closure.
3fill in blank
hardFix the error in the function call using trailing closure syntax.
Swift
func calculate(operation: (Int, Int) -> Int) -> Int {
return operation(3, 4)
}
let result = calculate [1] (3, 4) in
$0 + $1
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of braces for the closure.
Trying to put closure parameters inside the parentheses.
✗ Incorrect
Trailing closures use braces { } after the function call parentheses, not parentheses or other brackets.
4fill in blank
hardComplete the code to correctly use trailing closure syntax with a function that has two parameters, the second is a closure.
Swift
func fetchData(from url: String, completion: (String) -> Void) { completion("Data from \(url)") } fetchData(from: {BLANK_1}}) { data in print(data)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of braces for the closure.
Passing the URL outside the parentheses.
✗ Incorrect
The URL string is passed as the first argument inside parentheses, then the trailing closure starts with a brace.
5fill in blank
hardComplete the code to create a dictionary using trailing closure syntax with mapValues.
Swift
let numbers = ["one": 1, "two": 2, "three": 3] let strings = numbers.mapValues { number in String(number) + [1] "!" + }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of braces for the closure.
Using wrong string literals or missing the closing brace.
✗ Incorrect
The closure starts with {, concatenates the string "!", and ends with }.