0
0
Swiftprogramming~20 mins

Closures are reference types in Swift - Practice Problems & Coding Challenges

Choose your learning style9 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.