0
0
Swiftprogramming~10 mins

Closures as function parameters 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 closure that prints "Hello".

Swift
func greet(action: () -> Void) {
    action()
}

greet [1] {
    print("Hello")
}
Drag options to blanks, or click blank then click option'
A()
B(action: () -> Void)
C(action: () -> Void) -> Void
D() -> Void
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.
2fill in blank
medium

Complete 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'
A() -> Int
B(Int) -> Int
C(Int) -> Void
D(Int, Int) -> Int
Attempts:
3 left
💡 Hint
Common Mistakes
Using a closure type that returns Void instead of Int.
Using a closure type with no parameters.
3fill in blank
hard

Fix 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'
A(Bool, Bool) -> Int
B(Int) -> Bool
C(Int, Int) -> Bool
D() -> Bool
Attempts:
3 left
💡 Hint
Common Mistakes
Using a closure type with only one parameter.
Using a closure type with wrong parameter or return types.
4fill in blank
hard

Fill 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'
A() -> String
B(String) -> Void
C()
D() -> Void
Attempts:
3 left
💡 Hint
Common Mistakes
Using closure types that return Void instead of String.
Omitting parentheses when calling the function.
5fill in blank
hard

Complete 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'
A(String) -> Int
B{
C}
Din
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting braces around the closure body.
Forgetting the 'in' keyword in the closure syntax.