Bird
0
0

Given this SwiftUI code snippet, what will be the filtered list when the user types "cat" in the search bar?

medium📝 Predict Output Q4 of 15
iOS Swift - Lists and Data Display
Given this SwiftUI code snippet, what will be the filtered list when the user types "cat" in the search bar?
struct ContentView: View {
  @State private var searchText = ""
  let animals = ["cat", "dog", "caterpillar", "bird"]

  var filteredAnimals: [String] {
    if searchText.isEmpty { return animals }
    return animals.filter { $0.contains(searchText) }
  }

  var body: some View {
    List(filteredAnimals, id: \.self) { animal in
      Text(animal)
    }
    .searchable(text: $searchText)
  }
}
A["caterpillar"]
B["cat"]
C["cat", "caterpillar"]
D["dog", "bird"]
Step-by-Step Solution
Solution:
  1. Step 1: Understand filtering logic

    The filter checks if each animal contains the search text "cat" anywhere in the string.
  2. Step 2: Apply filter to list

    "cat" is contained in "cat" and "caterpillar", so both appear in the filtered list.
  3. Final Answer:

    ["cat", "caterpillar"] -> Option C
  4. Quick Check:

    Filter with contains("cat") = ["cat", "caterpillar"] [OK]
Quick Trick: Filter with contains matches substrings anywhere [OK]
Common Mistakes:
  • Assuming exact match only
  • Ignoring multiple matches
  • Returning unfiltered list

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes