Bird
Raised Fist0
Swiftprogramming~20 mins

Closures are reference types 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 Swift code using closures?

Consider the following Swift code. What will be printed?

Swift
func makeIncrementer() -> () -> Int {
    var total = 0
    let incrementer: () -> Int = {
        total += 1
        return total
    }
    return incrementer
}

let increment = makeIncrementer()
print(increment())
print(increment())
A2\n3
B0\n1
C1\n1
D1\n2
Attempts:
2 left
💡 Hint

Remember that closures capture variables by reference, so the variable total keeps its value between calls.

🧠 Conceptual
intermediate
1:30remaining
Why are closures considered reference types in Swift?

Choose the best explanation why closures in Swift behave as reference types.

ABecause closures capture variables and share the same instance when assigned or passed around.
BBecause closures are copied every time they are assigned to a new variable.
CBecause closures cannot capture variables from their surrounding context.
DBecause closures are stored on the stack and destroyed after use.
Attempts:
2 left
💡 Hint

Think about what happens when you assign a closure to multiple variables.

🔧 Debug
advanced
2:00remaining
What error occurs in this Swift closure code?

Examine the code below. What error will it produce when compiled?

Swift
func createClosure() -> () -> Int {
    var count = 0
    return {
        count += 1
        return count
    }
}

let closure1 = createClosure()
let closure2 = closure1
closure2 = createClosure()
AType mismatch: cannot assign closure to closure2
BNo error, code compiles and runs
CCannot assign to value: 'closure2' is a 'let' constant
DRuntime error: variable 'count' not captured
Attempts:
2 left
💡 Hint

Look at how closure2 is declared and used.

❓ Predict Output
advanced
2:00remaining
What is the output when modifying a captured variable through two closures?

What will this Swift code print?

Swift
func makeCounter() -> () -> Int {
    var count = 0
    return {
        count += 1
        return count
    }
}

let counter1 = makeCounter()
let counter2 = counter1
print(counter1())
print(counter2())
A1\n1
B1\n2
C2\n3
D0\n1
Attempts:
2 left
💡 Hint

Remember closures are reference types and share captured variables.

🚀 Application
expert
2:30remaining
How many unique closure instances are created here?

Given the code below, how many unique closure instances exist after execution?

Swift
func createClosure() -> () -> Int {
    var value = 0
    return {
        value += 1
        return value
    }
}

let c1 = createClosure()
let c2 = createClosure()
let c3 = c1
let c4 = c2
let c5 = c1
A2
B3
C5
D4
Attempts:
2 left
💡 Hint

Closures created by separate calls to createClosure() are unique instances.

Practice

(1/5)
1. What does it mean when we say closures are reference types in Swift?
easy
A. Multiple variables can point to the same closure instance, sharing changes.
B. Closures cannot capture variables from their surrounding context.
C. Each time you assign a closure, a new copy is created.
D. Closures are stored only as values, not references.

Solution

  1. Step 1: Understand what reference types mean

    Reference types mean multiple variables can point to the same instance in memory.
  2. Step 2: Apply this to closures

    Since closures are reference types, assigning them copies the reference, not the code itself.
  3. Final Answer:

    Multiple variables can point to the same closure instance, sharing changes. -> Option A
  4. Quick Check:

    Closures share instance references [OK]
Hint: Reference types share instances, not copies [OK]
Common Mistakes:
  • Thinking closures always create new copies
  • Confusing closures with value types like structs
  • Ignoring that closures capture variables by reference
2. Which of the following is the correct way to assign a closure to a variable in Swift?
easy
A. func closure = { print("Hello") }
B. let closure = { print("Hello") }
C. closure := { print("Hello") }
D. var closure = function printHello() {}

Solution

  1. Step 1: Recall Swift closure syntax

    Closures are assigned using curly braces and can be stored in variables with let or var.
  2. Step 2: Check each option

    let closure = { print("Hello") } uses correct syntax: let closure = { print("Hello") }.
  3. Final Answer:

    let closure = { print("Hello") } -> Option B
  4. Quick Check:

    Correct closure assignment syntax [OK]
Hint: Closures use curly braces and assign with let or var [OK]
Common Mistakes:
  • Using := which is not Swift syntax
  • Trying to declare closures like functions
  • Using func keyword incorrectly for closures
3. What will be printed by this Swift code?
var closureA = { print("Count: 0") }
var closureB = closureA
closureA = { print("Count: 1") }
closureB()
medium
A. Count: 0
B. Count: 1
C. No output, error occurs
D. Count: 0 and Count: 1

Solution

  1. Step 1: Understand closure assignment

    closureB is assigned closureA's original closure printing "Count: 0".
  2. Step 2: Reassign closureA

    closureA is changed to a new closure printing "Count: 1", but closureB still points to the old closure.
  3. Final Answer:

    Count: 0 -> Option A
  4. Quick Check:

    closureB keeps original closure [OK]
Hint: Reassigning closureA doesn't change closureB's reference [OK]
Common Mistakes:
  • Assuming closureB changes when closureA is reassigned
  • Confusing closure references with copies
  • Expecting both closures to print the same after reassignment
4. Identify the error in this Swift code involving closures:
var closure1 = { print("Hello") }
var closure2 = closure1
closure1 = { print("World") }
closure2 = closure1
medium
A. Closure syntax is invalid
B. Cannot assign closure1 to closure2 after reassignment
C. No error, code runs fine
D. Variables closure1 and closure2 must be constants

Solution

  1. Step 1: Check closure assignments

    Both closure1 and closure2 are variables and can be reassigned closures.
  2. Step 2: Validate syntax and assignments

    All closure assignments use correct syntax and valid variable usage.
  3. Final Answer:

    No error, code runs fine -> Option C
  4. Quick Check:

    Valid closure reassignment [OK]
Hint: Variables can be reassigned closures freely [OK]
Common Mistakes:
  • Thinking reassignment causes errors
  • Confusing closure syntax with function syntax
  • Assuming closures must be constants
5. Given this Swift code, what will be printed?
func makeCounter() -> () -> Int {
    var count = 0
    let increment: () -> Int = {
        count += 1
        return count
    }
    return increment
}

let counter1 = makeCounter()
let counter2 = counter1
print(counter1())
print(counter2())
hard
A. 1 and 1
B. 0 and 1
C. 2 and 2
D. 1 and 2

Solution

  1. Step 1: Understand closure capturing

    The closure increments and returns the same captured variable 'count'.
  2. Step 2: Analyze reference sharing

    counter1 and counter2 reference the same closure instance, so increments affect both.
  3. Step 3: Trace calls

    First call counter1() returns 1, second call counter2() increments count to 2 and returns 2.
  4. Final Answer:

    1 and 2 -> Option D
  5. Quick Check:

    Shared closure state increments count [OK]
Hint: Closures share captured variables and state [OK]
Common Mistakes:
  • Thinking counter2 is independent copy
  • Ignoring closure captures and shared state
  • Assuming count resets on each call
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