2 min read
Step 2: Habit List
Display habits and add new ones.
Where We Are
You have a basic app shell. Now let’s build the habit list.
Create the Data Model
Create a Habit model with:
- An ID (UUID)
- A name (String)
- A creation date
Use a simple Swift struct that conforms to Identifiable.
Display a List
Replace the "No habits yet" placeholder with a SwiftUI List.
- If there are no habits, show "No habits yet. Tap + to start."
- If there are habits, show each one by name
- Add a toolbar button (+) to add new habits
Add New Habits
When the user taps +, show a sheet with:
- A text field for the habit name
- A "Save" button that adds the habit and closes the sheet
- A "Cancel" button that closes without saving
- Don't allow saving if the name is empty
Test It
- Run the app
- Tap + to add a habit
- Type “Drink water” and save
- Add a few more: “Exercise”, “Read”, “Meditate”
- You should see them in the list
The data won’t persist yet — if you restart the app, the habits disappear. That’s fine for now.
Checkpoint
By now you should have:
- Habit list displays correctly
- Can add habits via the + button
- Sheet appears with text input
- Empty names are rejected
What You Learned
- SwiftUI List and ForEach
- Sheets and modal presentation
- State management with @State
- Data modeling with structs