Bird
0
0

Find the problem in this Swift code snippet:

medium📝 Debug Q7 of 15
Swift - Functions
Find the problem in this Swift code snippet:
func outer() {
  func inner() {
    print(message)
  }
  let message = "Hello"
  inner()
}
outer()
Aprint statement syntax is incorrect
Bmessage must be a global variable
Cinner() must be called before message declaration
Dinner() cannot access message declared after it
Step-by-Step Solution
Solution:
  1. Step 1: Check variable scope and declaration order

    message is declared after inner(), so inner() cannot access it because it is not yet defined.
  2. Step 2: Understand Swift's variable visibility rules

    Variables must be declared before use in the same scope or accessible via closure capture.
  3. Final Answer:

    inner() cannot access message declared after it -> Option D
  4. Quick Check:

    Variable must be declared before use in nested function [OK]
Quick Trick: Declare variables before nested functions that use them [OK]
Common Mistakes:
  • Assuming nested functions see variables declared later
  • Thinking variables must be global
  • Calling nested function before variable declaration

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes