0
0
Swiftprogramming~20 mins

Nested functions in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Nested Functions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of nested function call
What is the output of this Swift code with nested functions?
Swift
func outer() -> String {
    func inner() -> String {
        return "Hello"
    }
    return inner() + " World"
}
print(outer())
AHello World
BWorld
CHello
DCompilation error
Attempts:
2 left
💡 Hint
Look at how the inner function is called and combined with a string.
Predict Output
intermediate
2:00remaining
Value returned by nested function with parameter
What value does the function call outer(3) return in this Swift code?
Swift
func outer(_ x: Int) -> Int {
    func inner(_ y: Int) -> Int {
        return y * 2
    }
    return inner(x) + 1
}
let result = outer(3)
A7
B6
C8
DCompilation error
Attempts:
2 left
💡 Hint
Calculate inner(3) first, then add 1.
🔧 Debug
advanced
2:00remaining
Identify the error in nested function usage
What error does this Swift code produce when compiled?
Swift
func outer() {
    func inner() {
        print("Inside inner")
    }
}
inner()
AError: Missing return in function expected to return value
BError: Use of unresolved identifier 'inner'
CNo error, prints "Inside inner"
DError: Function 'outer' must be called before 'inner'
Attempts:
2 left
💡 Hint
Check the scope of the inner function.
Predict Output
advanced
2:00remaining
Output of nested function modifying outer variable
What is printed by this Swift code?
Swift
func outer() -> Int {
    var count = 0
    func inner() {
        count += 1
    }
    inner()
    inner()
    return count
}
print(outer())
ACompilation error
B0
C1
D2
Attempts:
2 left
💡 Hint
Consider how many times inner() changes count.
🧠 Conceptual
expert
3:00remaining
Behavior of nested functions and variable capture
Consider this Swift code. What is the output when calling outer()?
Swift
func outer() -> () -> Int {
    var x = 0
    func inner() -> Int {
        x += 1
        return x
    }
    return inner
}
let f = outer()
print(f())
print(f())
A
0
0
B
1
1
C
1
2
DCompilation error
Attempts:
2 left
💡 Hint
Think about how the inner function remembers the variable x.