SwiftUI series 7: Building a Simple Fruit Search App in SwiftUI

In this tutorial, we'll create a simple yet effective fruit search application using SwiftUI. This app will demonstrate how to implement a search functionality with a list of fruits. Let's break down the code and understand each component.

Setting Up the Project

First, create a new SwiftUI project and add a new file called SearchView.swift. This will be our main view containing the search functionality.

The Code Structure

import SwiftUI

struct SearchView: View {
    @State private var searchText = ""
    let names = ["Apple","Banana","Orange","Mango","Strawberry","Pineapple","Grape","Kiwi"]

    // ... rest of the code
}

Key Components:

  1. State Variable:

    • We declare searchText as a @State variable to store the user's search input
      @State private var searchText = ""
  2. Fruit Data:

    • A simple array of fruit names
      let names = ["Apple","Banana","Orange","Mango","Strawberry","Pineapple","Grape","Kiwi"]
  3. Search Filter Logic:

    var filteredNames: [String] {
       if searchText.isEmpty {
           return names
       } else {
           return names.filter { $0.lowercased().contains(searchText.lowercased()) }
       }
    }

    This computed property:

    • Returns all names if search text is empty
    • Filters names that contain the search text (case-insensitive)
  4. User Interface:

    var body: some View {
       NavigationStack {
           List(filteredNames, id: \.self) { name in
               Text(name)
           }
           .searchable(text: $searchText, placement: .automatic, prompt: "Search William Jiamin's Favorite Fruits ...")
           .navigationTitle("Search Fruits App")
       }
    }

Features Explained

  1. NavigationStack:

    • Provides navigation capabilities and proper layout structure
  2. List View:

    • Displays the filtered fruits in a scrollable list
    • Uses id: \.self for unique identification of list items
  3. Searchable Modifier:

    • Adds a search bar to the view
    • Binds to the searchText state variable
    • Includes a custom prompt message

How It Works

  1. When the app launches, it displays all fruits in the list
  2. As the user types in the search bar:
    • The searchText state updates
    • The filteredNames computed property filters the list
    • The List view automatically updates with filtered results

Conclusion

This simple yet functional implementation shows how easy it is to create a searchable list in SwiftUI. The code is concise and takes advantage of SwiftUI's declarative syntax and built-in search functionality.

Try adding more features like:

  • Custom fruit cell designs
  • Categories for fruits
  • Favorite fruit marking functionality

Happy coding! 🍎🍌🍊