Bird
0
0

Identify the error in this ObservableObject class:

medium📝 Debug Q6 of 15
iOS Swift - State Management in SwiftUI
Identify the error in this ObservableObject class:
class UserSettings: ObservableObject {
  @Published var username: String

  init() {
    username = "Guest"
  }
}
ANo error; the code is correct.
BObservableObject cannot have initializers.
CThe @Published property must be optional.
DMissing default value for @Published property.
Step-by-Step Solution
Solution:
  1. Step 1: Check @Published property initialization

    The property username is initialized in the init(), which is valid.
  2. Step 2: Confirm ObservableObject class rules

    ObservableObject classes can have initializers and non-optional @Published properties.
  3. Final Answer:

    No error; the code is correct. -> Option A
  4. Quick Check:

    ObservableObject with init and @Published is valid [OK]
Quick Trick: ObservableObject classes can have initializers and non-optional @Published [OK]
Common Mistakes:
  • Thinking @Published must have default value inline
  • Assuming ObservableObject cannot have init()
  • Believing @Published must be optional

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes