Bird
0
0

Identify the error in this Swift code:

medium📝 Debug Q14 of 15
Swift - Collections
Identify the error in this Swift code:
let items = []
items.append("apple")
ACannot append to a constant array declared with let.
BArray type cannot be inferred from empty array literal.
CAppending a String to an array of Ints causes error.
DNo error; code runs fine.
Step-by-Step Solution
Solution:
  1. Step 1: Check array declaration and type inference

    The array is declared as let items = [] with no type or initial values. Swift cannot guess the type from an empty array literal.
  2. Step 2: Understand why append fails

    Because items is declared with let, it is immutable and cannot be appended to. To append, it must be declared with var.
  3. Final Answer:

    Cannot append to a constant array declared with let. -> Option A
  4. Quick Check:

    let arrays are immutable [OK]
Quick Trick: let arrays cannot be modified after declaration [OK]
Common Mistakes:
  • Thinking append fails because array type is unknown
  • Assuming default array type is [Int]
  • Believing code runs without error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes