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 identifierHashable
: 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:
-
Category Management
var categories: [String] { Array(Set(fruits.map { $0.category})).sorted() }
This computed property provides a unique, sorted list of all fruit categories.
-
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?
-
Separation of Concerns
- Model (Fruit): Data structure
- ViewModel: Business logic
- View (to be implemented): UI presentation
-
Maintainability
- Easy to modify search logic
- Simple to add new fruit properties
- Clear separation between data and presentation
-
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!