Bird
Raised Fist0
Swiftprogramming~20 mins

Closure expression syntax in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Closure 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 closure expression?
Consider the following Swift code using a closure expression. What will be printed when this code runs?
Swift
let numbers = [1, 2, 3, 4]
let doubled = numbers.map({ (num: Int) -> Int in
    return num * 2
})
print(doubled)
A[4, 8, 12, 16]
B[1, 2, 3, 4]
CCompilation error
D[2, 4, 6, 8]
Attempts:
2 left
💡 Hint
Look at how the closure multiplies each number by 2.
❓ Predict Output
intermediate
2:00remaining
What does this shorthand closure print?
What is the output of this Swift code using shorthand argument names in a closure?
Swift
let names = ["Anna", "Alex", "Brian", "Jack"]
let sortedNames = names.sorted(by: { $0 > $1 })
print(sortedNames)
A["Jack", "Brian", "Alex", "Anna"]
BRuntime error
C["Alex", "Anna", "Brian", "Jack"]
D["Anna", "Alex", "Brian", "Jack"]
Attempts:
2 left
💡 Hint
The closure sorts names in descending order.
🔧 Debug
advanced
2:00remaining
Identify the error in this closure syntax
This Swift code tries to filter an array using a closure but causes a compile error. What is the error?
Swift
let numbers = [1, 2, 3, 4, 5]
let evens = numbers.filter { num in
    num % 2 == 0
}

print(evens)
AMissing closing brace '}' for the closure
BMissing return keyword inside the closure
CIncorrect use of parentheses in filter call
DUsing 'num' instead of '$0' causes error
Attempts:
2 left
💡 Hint
Check if all braces are properly closed.
❓ Predict Output
advanced
2:00remaining
What is the output of this nested closure?
What will this Swift code print when run?
Swift
func makeIncrementer(amount: Int) -> () -> Int {
    var total = 0
    return {
        total += amount
        return total
    }
}

let incrementByTen = makeIncrementer(amount: 10)
print(incrementByTen())
print(incrementByTen())
A0\n10
BCompilation error
C10\n20
D10\n10
Attempts:
2 left
💡 Hint
The closure captures and updates 'total' each time it is called.
🧠 Conceptual
expert
2:00remaining
Which option correctly explains trailing closure syntax?
In Swift, which statement best describes the trailing closure syntax?
ATrailing closures must always have explicit parameter types declared.
BA closure passed as the last argument can be written outside the parentheses of the function call.
CTrailing closures cannot capture variables from the surrounding context.
DTrailing closures are only allowed if the function has exactly one parameter.
Attempts:
2 left
💡 Hint
Think about how you can write closures after function calls.

Practice

(1/5)
1. What is a closure in Swift?
easy
A. A special kind of loop for repeating tasks
B. A block of code that can be passed around and executed later
C. A type of variable that stores numbers only
D. A keyword used to declare functions

Solution

  1. Step 1: Understand the definition of closure

    A closure is a block of code that can be saved and run later, similar to a function but more flexible.
  2. Step 2: Compare options with closure meaning

    Only 'A block of code that can be passed around and executed later' correctly describes a closure.
  3. Final Answer:

    A block of code that can be passed around and executed later -> Option B
  4. Quick Check:

    Closure = block of code passed and run later [OK]
Hint: Closures are like saved code blocks you run later [OK]
Common Mistakes:
  • Confusing closures with variables
  • Thinking closures are loops
  • Mixing closures with function keywords
2. Which of the following is the correct syntax for a closure that takes two Ints and returns their sum?
easy
A. { a, b in a + b }
B. { (a, b) -> Int { a + b } }
C. func sum(a: Int, b: Int) -> Int { return a + b }
D. { (a: Int, b: Int) -> Int in return a + b }

Solution

  1. Step 1: Identify closure syntax components

    A closure with parameters and return type uses parentheses for parameters, '->' for return type, and 'in' before the code.
  2. Step 2: Check each option

    { (a: Int, b: Int) -> Int in return a + b } correctly uses (a: Int, b: Int) -> Int in return a + b. { a, b in a + b } omits types and requires context for type inference to compile. func sum(a: Int, b: Int) -> Int { return a + b } is a function, not a closure. { (a, b) -> Int { a + b } } has wrong braces placement and misses 'in'.
  3. Final Answer:

    { (a: Int, b: Int) -> Int in return a + b } -> Option D
  4. Quick Check:

    Closure syntax = parameters, return type, in keyword [OK]
Hint: Closure syntax: parameters, arrow, return type, then 'in' [OK]
Common Mistakes:
  • Confusing functions with closures
  • Missing 'in' keyword
  • Incorrect braces placement
3. What is the output of this Swift code?
let multiply = { (x: Int, y: Int) -> Int in x * y }
print(multiply(3, 4))
medium
A. 12
B. 7
C. 34
D. Error

Solution

  1. Step 1: Understand closure definition and call

    The closure multiply takes two Ints and returns their product (x * y). It is called with 3 and 4.
  2. Step 2: Calculate the result

    3 * 4 = 12, so print outputs 12.
  3. Final Answer:

    12 -> Option A
  4. Quick Check:

    3 times 4 = 12 [OK]
Hint: Multiply inputs inside closure to get output [OK]
Common Mistakes:
  • Adding instead of multiplying
  • Concatenating numbers as strings
  • Syntax errors in closure call
4. Find the error in this closure syntax:
let greet = { name: String in
  print("Hello, \(name)!")
}
medium
A. Parameters must be in parentheses
B. Missing 'in' keyword after parameters
C. Closure cannot print inside its body
D. Missing parameter types in closure

Solution

  1. Step 1: Check closure parameter syntax

    Closure parameters must be enclosed in parentheses, like (name: String).
  2. Step 2: Identify the error in given code

    The code uses 'name: String' without parentheses, which is invalid syntax.
  3. Final Answer:

    Parameters must be in parentheses -> Option A
  4. Quick Check:

    Closure parameters need parentheses [OK]
Hint: Always put closure parameters inside parentheses [OK]
Common Mistakes:
  • Omitting parentheses around parameters
  • Forgetting 'in' keyword
  • Thinking closures can't print
5. How can you simplify this closure expression?
let numbers = [1, 2, 3, 4]
let doubled = numbers.map({ (num: Int) -> Int in return num * 2 })
print(doubled)
hard
A. Use a for loop instead of map
B. Remove 'return' and keep full syntax: numbers.map { (num: Int) -> Int in num * 2 }
C. Use shorthand argument names: numbers.map { $0 * 2 }
D. Cannot simplify closure expressions

Solution

  1. Step 1: Understand closure simplification rules

    Swift allows removing parameter types and 'return' when the closure is a single expression, and using shorthand $0 for first parameter.
  2. Step 2: Apply shorthand argument names

    Replacing full closure with numbers.map { $0 * 2 } simplifies code and is correct.
  3. Final Answer:

    Use shorthand argument names: numbers.map { $0 * 2 } -> Option C
  4. Quick Check:

    Shorthand $0 replaces explicit parameters [OK]
Hint: Use $0, $1 for closure parameters to shorten code [OK]
Common Mistakes:
  • Keeping full syntax unnecessarily
  • Thinking closures can't be simplified
  • Replacing map with loops unnecessarily
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