0
0
Swiftprogramming~10 mins

Trailing closure syntax in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A() -> Void
B()()
C()
D(action:)
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the parentheses when the function requires them.
Trying to put the closure inside the parentheses.
2fill in blank
medium

Complete 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'
A()
B(task:)
C() -> Void
D(task)
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to name the closure parameter in the call.
Omitting the parentheses entirely.
3fill in blank
hard

Fix 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'
A<
B(
C[
D{
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of braces for the closure.
Trying to put closure parameters inside the parentheses.
4fill in blank
hard

Complete 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'
A"https://api.example.com"
B{
C(
D"example.com"
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of braces for the closure.
Passing the URL outside the parentheses.
5fill in blank
hard

Complete 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'
A{
B"!"
C"?"
D}
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of braces for the closure.
Using wrong string literals or missing the closing brace.