BLACK FRIDAY SALE: Save big on all my Swift books and bundles! >>

Searching for data in a List

Paul Hudson    @twostraws   

Before our List view is done, we’re going to add a SwiftUI modifier that makes our user’s experience a whole lot better without too much work: searchable(). Adding this will allow users to filter the list of resorts we’re showing, making it easy to find the exact thing they’re looking for.

This takes only four steps, starting with a new @State property in ContentView to store the text the user is searching for:

@State private var searchText = ""

Second, we can bind that to our List in ContentView by adding this directly below the existing navigationTitle() modifier:

.searchable(text: $searchText, prompt: "Search for a resort")

Third, we need a computed property that will handle the filtering of our data. If our new searchText property is empty then we can just send back all the resorts we loaded, otherwise we’ll use localizedCaseInsensitiveContains() to filter the array based on their search criteria:

var filteredResorts: [Resort] {
    if searchText.isEmpty {
        return resorts
    } else {
        return resorts.filter { $0.name.localizedCaseInsensitiveContains(searchText) }
    }
}

And the final step is to use filteredResorts as the data source for our list, like this:

List(filteredResorts) { resort in

And with that we’re done! If you run the app again you’ll see you can drag the resort list gently down to see the search box, and entering something in there will filter the list straight away. Honestly, searchable() is one of the biggest “bang for buck” features in SwiftUI – it’s such an important feature for users, and took us only a few minutes to implement!

Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.