WWDC22 SALE: Save 50% 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 Fernando Olivares

SPONSORED Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!

Read the book

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

Buy Pro Swift 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 (Vapor Edition) 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 Server-Side Swift (Kitura Edition) 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.