Bird
Raised Fist0
Swiftprogramming~20 mins

Closures as function parameters in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Closures Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Swift code using a closure parameter?

Consider this Swift function that takes a closure as a parameter and calls it:

func greetUser(name: String, action: (String) -> String) {
    let message = action(name)
    print(message)
}

greetUser(name: "Anna") { userName in
    return "Hello, \(userName)!"
}

What will be printed when this code runs?

Swift
func greetUser(name: String, action: (String) -> String) {
    let message = action(name)
    print(message)
}

greetUser(name: "Anna") { userName in
    return "Hello, \(userName)!"
}
AHello, userName!
BHello, Anna!
CgreetUser(name: "Anna")
DError: Missing return statement
Attempts:
2 left
💡 Hint

Look at how the closure uses the parameter userName inside the string.

❓ Predict Output
intermediate
2:00remaining
What does this Swift code print when using a trailing closure?

Examine this Swift code that uses a trailing closure syntax:

func performOperation(_ a: Int, _ b: Int, operation: (Int, Int) -> Int) {
    let result = operation(a, b)
    print(result)
}

performOperation(4, 5) { x, y in
    x * y
}

What is the output?

Swift
func performOperation(_ a: Int, _ b: Int, operation: (Int, Int) -> Int) {
    let result = operation(a, b)
    print(result)
}

performOperation(4, 5) { x, y in
    x * y
}
AError: Missing return in closure
B9
C45
D20
Attempts:
2 left
💡 Hint

Remember that the closure multiplies the two numbers.

🔧 Debug
advanced
2:00remaining
What error does this Swift code produce?

Look at this Swift function call with a closure parameter:

func calculate(value: Int, operation: (Int) -> Int) {
    let result = operation(value)
    print(result)
}

calculate(value: 10) { number in
    if number > 5 {
        number * 2
    }
}

What error will this code cause when compiled?

Swift
func calculate(value: Int, operation: (Int) -> Int) {
    let result = operation(value)
    print(result)
}

calculate(value: 10) { number in
    if number > 5 {
        number * 2
    }
}
AError: Missing return in closure
BRuntime error: nil value
CNo error, prints 20
DSyntax error: unexpected if statement
Attempts:
2 left
💡 Hint

Check if the closure always returns a value.

🧠 Conceptual
advanced
2:00remaining
Which option correctly describes escaping closures in Swift?

In Swift, what does it mean when a closure parameter is marked with @escaping?

AThe closure can be stored and called after the function returns
BThe closure must be called immediately inside the function
CThe closure cannot capture variables from its surrounding context
DThe closure is automatically executed on the main thread
Attempts:
2 left
💡 Hint

Think about when the closure might be used relative to the function call.

❓ Predict Output
expert
3:00remaining
What is the output of this Swift code using nested closures?

Analyze this Swift code with nested closures passed as parameters:

func outerFunction(action: (Int) -> (Int) -> Int) {
    let innerClosure = action(3)
    let result = innerClosure(4)
    print(result)
}

outerFunction { x in
    return { y in
        x + y
    }
}

What will be printed?

Swift
func outerFunction(action: (Int) -> (Int) -> Int) {
    let innerClosure = action(3)
    let result = innerClosure(4)
    print(result)
}

outerFunction { x in
    return { y in
        x + y
    }
}
A12
BError: Cannot convert closure type
C7
D34
Attempts:
2 left
💡 Hint

Trace the values of x and y through the closures.

Practice

(1/5)
1.

What is the main purpose of passing a closure as a function parameter in Swift?

easy
A. To allow the function to execute custom code provided by the caller
B. To make the function run faster
C. To prevent the function from returning a value
D. To declare a global variable inside the function

Solution

  1. Step 1: Understand what a closure is

    A closure is a block of code that can be passed around and executed later.
  2. Step 2: Understand why closures are passed to functions

    Passing a closure lets the function run custom code without changing its own code.
  3. Final Answer:

    To allow the function to execute custom code provided by the caller -> Option A
  4. Quick Check:

    Closures customize function behavior = A [OK]
Hint: Closures let functions run your code inside them [OK]
Common Mistakes:
  • Thinking closures speed up the function
  • Confusing closures with variables
  • Believing closures stop function returns
2.

Which of the following is the correct syntax to declare a function that takes a closure parameter with no input and no return value?

func performAction(____) { }
easy
A. action: () => Void
B. action: Void -> ()
C. action: () -> () -> Void
D. action: () -> Void

Solution

  1. Step 1: Recall closure syntax in Swift

    A closure with no input and no return is written as () -> Void.
  2. Step 2: Match syntax to function parameter

    The parameter should be named and typed as action: () -> Void.
  3. Final Answer:

    action: () -> Void -> Option D
  4. Quick Check:

    Closure type syntax = D [OK]
Hint: Closure type: inputs in (), arrow, then return type [OK]
Common Mistakes:
  • Using 'Void -> ()' which is invalid
  • Adding extra arrows like '() -> () -> Void'
  • Using '=>' which is not Swift syntax
3.

What will be printed when the following Swift code runs?

func greet(action: () -> String) {
    print("Greeting: " + action())
}

greet { "Hello, Swift!" }
medium
A. Hello, Swift!
B. Greeting: action
C. Greeting: Hello, Swift!
D. Error: Missing return type

Solution

  1. Step 1: Understand the function call

    The function greet takes a closure that returns a String and prints "Greeting: " plus the closure's result.
  2. Step 2: Evaluate the closure passed

    The closure returns "Hello, Swift!", so the print statement outputs "Greeting: Hello, Swift!".
  3. Final Answer:

    Greeting: Hello, Swift! -> Option C
  4. Quick Check:

    Closure returns string printed with prefix = A [OK]
Hint: Closure returns string, function prints with prefix [OK]
Common Mistakes:
  • Expecting just the closure string without prefix
  • Confusing closure name with output
  • Thinking code causes error
4.

Identify the error in this Swift function that takes a closure parameter:

func repeatTask(times: Int, task: () -> Void) {
    for _ in 1...times {
        task
    }
}
medium
A. The closure 'task' is not called with parentheses
B. The loop range should start from 0
C. The closure parameter must return a value
D. The function must return a value

Solution

  1. Step 1: Check how the closure is used inside the loop

    The code uses 'task' without parentheses, so the closure is not executed.
  2. Step 2: Correct closure call syntax

    To run the closure, it must be called as 'task()' with parentheses.
  3. Final Answer:

    The closure 'task' is not called with parentheses -> Option A
  4. Quick Check:

    Call closure with () to execute = C [OK]
Hint: Call closures with () to run them [OK]
Common Mistakes:
  • Forgetting parentheses to call closure
  • Changing loop range unnecessarily
  • Expecting closure to return value when void
5.

Given this function that filters numbers using a closure, how would you call it to get only even numbers?

func filterNumbers(_ numbers: [Int], using condition: (Int) -> Bool) -> [Int] {
    var result = [Int]()
    for number in numbers {
        if condition(number) {
            result.append(number)
        }
    }
    return result
}

Choose the correct call:

hard
A. filterNumbers([1,2,3,4]) { number in number * 2 }
B. filterNumbers([1,2,3,4]) { $0 % 2 == 0 }
C. filterNumbers([1,2,3,4]) { _ in true }
D. filterNumbers([1,2,3,4]) { $0 > 5 }

Solution

  1. Step 1: Understand the closure parameter

    The closure takes an Int and returns Bool to decide if number is included.
  2. Step 2: Identify condition for even numbers

    Even numbers satisfy number % 2 == 0, so closure should return true for those.
  3. Step 3: Match correct call

    filterNumbers([1,2,3,4]) { $0 % 2 == 0 } uses shorthand $0 % 2 == 0, which returns true for even numbers.
  4. Final Answer:

    filterNumbers([1,2,3,4]) { $0 % 2 == 0 } -> Option B
  5. Quick Check:

    Closure returns true for even numbers = B [OK]
Hint: Use $0 % 2 == 0 to filter even numbers [OK]
Common Mistakes:
  • Returning number * 2 instead of Bool
  • Returning always true to get all numbers
  • Filtering numbers greater than 5 instead of even
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard