Challenge - 5 Problems
Nested Functions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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())
Attempts:
2 left
💡 Hint
Look at how the inner function is called and combined with a string.
✗ Incorrect
The inner function returns "Hello". The outer function calls inner() and adds " World", so the output is "Hello World".
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Calculate inner(3) first, then add 1.
✗ Incorrect
inner(3) returns 3 * 2 = 6. Adding 1 gives 7, so outer(3) returns 7.
🔧 Debug
advanced2: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()
Attempts:
2 left
💡 Hint
Check the scope of the inner function.
✗ Incorrect
The inner function is defined inside outer and is not visible outside. Calling inner() outside causes an unresolved identifier error.
❓ Predict Output
advanced2: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())
Attempts:
2 left
💡 Hint
Consider how many times inner() changes count.
✗ Incorrect
inner() increments count by 1 each call. Called twice, count becomes 2, which is returned and printed.
🧠 Conceptual
expert3: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())
Attempts:
2 left
💡 Hint
Think about how the inner function remembers the variable x.
✗ Incorrect
The inner function captures x by reference. Each call to f() increments x, so outputs are 1 then 2.