0

I'm following this tutorial on adding a search bar in SwiftUI.

It doesn't work if i search by only typing with lower case letters when a name starts with higher case letters and vice versa. This is for a macOS app.

enter image description here

import SwiftUI

struct ContentView: View {
    let names = ["Holly", "Josh", "Rhonda", "Ted"]
    @State private var searchText = ""
    var body: some View {
        ScrollView {
            VStack(spacing: 20) {
                ForEach(searchResults, id: \.self) { name in
                    Text(name)
                        .foregroundColor(.white)
                        .font(.largeTitle)
                        .frame(width: 330, height: 100)
                        .background(Color.red)
                }
                .searchable(text: $searchText)
            
            }
            
        }
        
        .frame(width: 350,height: 350)
    }
    
    var searchResults: [String] {
          if searchText.isEmpty {
              return names
          } else {
              return names.filter { $0.contains(searchText) }
          }
      }
}
swiftnoob
  • 303
  • 1
  • 5
  • 21

2 Answers2

4

There is a dedicated API

return names.filter { $0.localizedCaseInsensitiveContains(searchText) }
vadian
  • 274,689
  • 30
  • 353
  • 361
1

If you would like to ignore case, you could convert the search criteria and the content you're searching to lowercase in this line

return names.filter { $0.contains(searchText) }

You could use the .lowercased() method.

Fredrik
  • 971
  • 8
  • 23