Bird
Raised Fist0
Swiftprogramming~20 mins

Why closures are fundamental in Swift - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Closure Mastery
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 closure example?
Consider this Swift code that uses a closure to add two numbers. What will be printed?
Swift
let add: (Int, Int) -> Int = { (a, b) in a + b }
print(add(3, 5))
A8
BError: Missing return statement
C35
D0
Attempts:
2 left
💡 Hint
Closures can be assigned to variables and called like functions.
🧠 Conceptual
intermediate
1:30remaining
Why are closures fundamental in Swift?
Which of these best explains why closures are fundamental in Swift?
AThey are used only to create classes and structs.
BThey are only used for asynchronous programming and have no other use.
CThey replace all functions and methods in Swift.
DThey allow you to write inline, self-contained blocks of code that can capture and store references to variables and constants from the surrounding context.
Attempts:
2 left
💡 Hint
Think about how closures can remember values from where they were created.
🔧 Debug
advanced
2:00remaining
What error does this closure code produce?
Look at this Swift code using a closure. What error will it cause?
Swift
var counter = 0
let incrementer = { counter += 1 }
incrementer()
print(counter)
AError: Cannot assign to value: 'counter' is a 'let' constant
BNo error, prints 1
CError: Closure cannot capture mutable variable
DError: Missing return in closure
Attempts:
2 left
💡 Hint
Check if the variable is mutable and if the closure modifies it.
❓ Predict Output
advanced
2:30remaining
What is the output of this closure capturing example?
What will this Swift code print?
Swift
func makeIncrementer(amount: Int) -> () -> Int {
    var total = 0
    let incrementer: () -> Int = {
        total += amount
        return total
    }
    return incrementer
}

let incrementByTen = makeIncrementer(amount: 10)
print(incrementByTen())
print(incrementByTen())
A
0
10
B
10
10
C
10
20
DError: Cannot capture 'total' in closure
Attempts:
2 left
💡 Hint
Closures can capture and modify variables from their creation context.
🚀 Application
expert
2:00remaining
How many items are in the resulting array after using this closure?
What is the count of elements in the array 'results' after running this Swift code?
Swift
let numbers = [1, 2, 3, 4, 5]
let results = numbers.map { num in
    if num % 2 == 0 {
        return num * 2
    } else {
        return num
    }
}
print(results.count)
A5
B3
C2
D0
Attempts:
2 left
💡 Hint
The map function returns an array with the same number of elements as the original.

Practice

(1/5)
1. What is a closure in Swift?
Closures are best described as:
easy
A. A type of variable that stores numbers
B. Blocks of code that can be saved and used later
C. A special kind of loop
D. A way to declare constants

Solution

  1. Step 1: Understand the definition of closures

    Closures are self-contained blocks of functionality that can be passed around and used in your code.
  2. Step 2: Match the description to the options

    Blocks of code that can be saved and used later correctly describes closures as blocks of code saved for later use, unlike variables, loops, or constants.
  3. Final Answer:

    Blocks of code that can be saved and used later -> Option B
  4. Quick Check:

    Closure = reusable code block [OK]
Hint: Closures are like saved recipes for code [OK]
Common Mistakes:
  • Confusing closures with variables
  • Thinking closures are loops
  • Mixing closures with constants
2. Which of the following is the correct syntax to declare a closure that explicitly takes no parameters and returns an Int?
easy
A. let closure = { () -> Int in return 5 }
B. let closure = (Int) -> { 5 }
C. let closure = { return 5 }
D. let closure = func() -> Int { 5 }

Solution

  1. Step 1: Recall closure syntax in Swift

    A closure with no parameters and returning Int is declared as { () -> Int in ... }.
  2. Step 2: Check each option

    let closure = { () -> Int in return 5 } matches the correct syntax. let closure = { return 5 } misses return type and parameters. let closure = (Int) -> { 5 } is invalid syntax. let closure = func() -> Int { 5 } uses function syntax, not closure.
  3. Final Answer:

    let closure = { () -> Int in return 5 } -> Option A
  4. Quick Check:

    Closure syntax = { () -> ReturnType in code } [OK]
Hint: Closure syntax uses braces with 'in' keyword [OK]
Common Mistakes:
  • Omitting 'in' keyword
  • Using function syntax instead of closure
  • Missing return type when needed
3. What will be printed by this Swift code?
let multiplyByTwo = { (number: Int) -> Int in
    return number * 2
}
print(multiplyByTwo(4))
medium
A. Error
B. 4
C. 2
D. 8

Solution

  1. Step 1: Understand the closure behavior

    The closure takes an Int and returns that number multiplied by 2.
  2. Step 2: Calculate the output for input 4

    4 * 2 = 8, so the print statement outputs 8.
  3. Final Answer:

    8 -> Option D
  4. Quick Check:

    4 * 2 = 8 [OK]
Hint: Multiply input by 2 inside closure [OK]
Common Mistakes:
  • Confusing input and output values
  • Expecting the closure to print automatically
  • Syntax errors in closure call
4. Identify the error in this closure declaration:
let greet = { name: String in
    print("Hello, \(name)!")
}
medium
A. Missing parentheses around parameters
B. Missing 'in' keyword
C. Closure must return a value
D. Incorrect print syntax

Solution

  1. Step 1: Check closure parameter syntax

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

    The code misses parentheses around parameters.
  3. Final Answer:

    Missing parentheses around parameters -> Option A
  4. Quick Check:

    Parameters need types in parentheses [OK]
Hint: Always put parameters and types in parentheses [OK]
Common Mistakes:
  • Omitting parentheses around parameters
  • Forgetting parameter types
  • Assuming closures must return values
5. How can closures capture values from their surrounding context?
Consider this code:
func makeIncrementer(amount: Int) -> () -> Int {
    var total = 0
    let incrementer: () -> Int = {
        total += amount
        return total
    }
    return incrementer
}

let incrementByTen = makeIncrementer(amount: 10)
print(incrementByTen())
print(incrementByTen())

What will be the output?
hard
A. 0 and 10
B. 10 and 10
C. 10 and 20
D. Error because total is not accessible

Solution

  1. Step 1: Understand closure capturing

    The closure captures the variable 'total' from its surrounding context and modifies it each time it runs.
  2. Step 2: Trace the output of two calls

    First call adds 10 to total (0 + 10 = 10), second call adds 10 again (10 + 10 = 20).
  3. Final Answer:

    10 and 20 -> Option C
  4. Quick Check:

    Closures capture and update variables [OK]
Hint: Closures remember and update outside variables [OK]
Common Mistakes:
  • Assuming closures do not keep state
  • Thinking total resets each call
  • Expecting errors due to variable scope
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