Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

SwiftUI series 9: Building a Fruit Search App: Data Model and ViewModel Implementation

In this tutorial, we'll explore how to create a robust data structure and view model for our Fruit Search App. We'll cover the data model, sample data, and the view model that handles our search logic.

1. Creating the Fruit Model

First, let's look at our Fruit model structure:

struct Fruit: Identifiable, Hashable {
    let id = UUID()
    let name: String
    let emoji: String
    let category: String
    let vitamins: String
}

Key Points:

  • Identifiable: Allows each fruit to have a unique identifier
  • Hashable: Enables the use of fruits in Sets and as dictionary keys
  • Properties include basic fruit information like name, emoji, category, and vitamins

2. Sample Data Implementation

We extend the Fruit model to include sample data:

extension Fruit {
    static let sampleFruits: [Fruit] = [
        Fruit(name: "Apple", emoji: "", category: "Core Fruits", vitamins: "C, B"),
        Fruit(name: "Banana", emoji: "", category: "Tropical", vitamins: "B6, C"),
        // ... more fruits
    ]
}

This provides us with a variety of fruits across different categories for testing and development.

3. FruitViewModel Implementation

The ViewModel serves as the brain of our application:

class FruitViewModel: ObservableObject {
    @Published var searchText = ""
    @Published var selectedCategory: String? = nil

    private let fruits: [Fruit]

    init(fruits: [Fruit] = Fruit.sampleFruits) {
        self.fruits = fruits
    }

Key Features:

  1. Category Management

    var categories: [String] {
    Array(Set(fruits.map { $0.category})).sorted()
    }

    This computed property provides a unique, sorted list of all fruit categories.

  2. Search and Filter Logic

    var filteredFruits: [Fruit] {
    let filtered = fruits.filter { fruit in
        searchText.isEmpty ? true :
        fruit.name.lowercased().contains(searchText.lowercased()) ||
        fruit.category.lowercased().contains(searchText.lowercased())
    }
    
    if let selectedCategory = selectedCategory {
        return filtered.filter { $0.category == selectedCategory }
    }
    
    return filtered
    }

The filtering logic includes:

  • Case-insensitive search in both name and category
  • Optional category filtering
  • Returns all fruits if search text is empty

Why This Architecture?

  1. Separation of Concerns

    • Model (Fruit): Data structure
    • ViewModel: Business logic
    • View (to be implemented): UI presentation
  2. Maintainability

    • Easy to modify search logic
    • Simple to add new fruit properties
    • Clear separation between data and presentation
  3. Scalability

    • Ready for real API integration
    • Easy to add more filtering options
    • Prepared for future features

Next Steps

In the next part of this tutorial, we'll implement the views that will use this ViewModel to create an interactive and responsive user interface. Stay tuned for the implementation of both the basic and better search views!