Bird
0
0

Why does the following SwiftUI code produce a compile-time error?

medium📝 Debug Q7 of 15
iOS Swift - Lists and Data Display
Why does the following SwiftUI code produce a compile-time error?
@State private var searchText = ""
let items = ["apple", "banana"]

var body: some View {
  List(filteredItems, id: \.self) { item in
    Text(item)
  }
  .searchable(text: $searchText)
}

var filteredItems: [String] {
  items.filter { $0.contains(searchText) }
}
ABecause <code>filteredItems</code> is not marked as <code>var</code> or <code>func</code> inside the View struct.
BBecause <code>searchText</code> is not initialized properly.
CBecause <code>List</code> cannot use <code>id: \.self</code> for strings.
DBecause <code>searchable</code> modifier cannot be applied to a List.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze filteredItems

    The filteredItems property is computed but declared outside the View's body or struct context.
  2. Step 2: SwiftUI requires computed properties inside the View struct

    Computed properties like filteredItems must be inside the View struct and marked as var.
  3. Step 3: Error cause

    Defining filteredItems outside or without var causes a compile error.
  4. Final Answer:

    Because filteredItems is not marked as var or func inside the View struct. -> Option A
  5. Quick Check:

    Computed properties must be inside View struct [OK]
Quick Trick: Computed properties must be inside View struct as var [OK]
Common Mistakes:
  • Assuming searchText initialization is wrong
  • Thinking List cannot use id: \.self
  • Believing searchable cannot be applied to List

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes