GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

Searching for data in a List

Paul Hudson    @twostraws   

Before the list in ContentView 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 navigationDestination() 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 localizedStandardContains() to filter the array based on their search criteria:

var filteredResorts: [Resort] {
    if searchText.isEmpty {
       resorts
    } else {
        resorts.filter { $0.name.localizedStandardContains(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 Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure and A/B test your entire paywall UI without any code changes or app updates.

Learn more here

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.