Bird
0
0

What is the issue with this Swift code snippet?

medium📝 Debug Q7 of 15
Swift - Collections
What is the issue with this Swift code snippet?
var data = []
data.append(10)
AThe append method is not available for arrays in Swift.
BYou cannot append elements to a variable declared with 'var'.
CThe array 'data' has no type specified, so Swift cannot infer the element type.
DThe array must be declared with 'let' to allow appending.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the declaration

    The array 'data' is declared as an empty array with no type annotation, so Swift cannot infer its element type.
  2. Step 2: Understand type inference rules

    Swift requires either explicit type annotation or initial elements to infer the array's type.
  3. Step 3: Identify the error

    Since 'data' has no type, calling 'append(10)' causes a compile-time error.
  4. Final Answer:

    The array 'data' has no type specified, so Swift cannot infer the element type. -> Option C
  5. Quick Check:

    Empty array without type annotation cannot infer element type [OK]
Quick Trick: Empty arrays need explicit type for appending [OK]
Common Mistakes:
  • Assuming 'var' prevents appending
  • Thinking append is unavailable for arrays
  • Believing 'let' is required for appending

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes