Bird
0
0

Identify the error in this Swift code:

medium📝 Debug Q6 of 15
iOS Swift - Swift Language Essentials
Identify the error in this Swift code:
struct Person {
  var name: String
}

var p1 = Person(name: "Alice")
p1.name = "Bob"
ACannot assign to property of a struct instance declared with let
BNo error, code is correct
CMissing initializer for struct
DCannot assign to property of a struct instance declared with var
Step-by-Step Solution
Solution:
  1. Step 1: Check mutability of struct instance

    p1 is declared with var, so it is mutable.
  2. Step 2: Verify property assignment

    Assigning to p1.name is allowed since p1 is mutable.
  3. Final Answer:

    No error, code is correct -> Option B
  4. Quick Check:

    Mutable struct instance allows property changes = A [OK]
Quick Trick: Use var to allow changing struct properties, let makes it immutable [OK]
Common Mistakes:
  • Assuming struct properties are always immutable
  • Confusing var and let for instance mutability
  • Expecting error without let declaration

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes