App 9 — 24 Apps You Can Make Today

John's Favorite Animals

A scrollable list of animals — your first data-driven view using List and a simple struct.

  • ios
↓ Download Playgrounds File

Lists of things are everywhere in apps. This one shows John's favorite animals — a scrollable list where each row shows the animal's name and a little description. It's your introduction to data-driven views.

What you'll build

A scrollable list of animals, each with a name and a fact. The list is generated from an array of data, not written out one row at a time.

Key concepts

A simple struct — Define a type to hold each animal's data. A struct groups related values together.

struct Animal: Identifiable {
    let id = UUID()
    let name: String
    let emoji: String
    let fact: String
}

Identifiable — The List and ForEach need to tell rows apart. Conforming to Identifiable (by adding an id property) gives them that.

An array of data — Create the list of animals as an array.

let animals = [
    Animal(name: "Axolotl",   emoji: "🦎", fact: "Can regrow lost limbs."),
    Animal(name: "Capybara",  emoji: "🐾", fact: "Very relaxed. Gets along with everyone."),
    Animal(name: "Mantis shrimp", emoji: "🦐", fact: "Sees 16 types of color receptors."),
]

List with ForEach — Hand your array to List (or use ForEach inside one) and SwiftUI creates a row for each item.

List(animals) { animal in
    HStack {
        Text(animal.emoji).font(.largeTitle)
        VStack(alignment: .leading) {
            Text(animal.name).font(.headline)
            Text(animal.fact).font(.caption).foregroundStyle(.secondary)
        }
    }
}

Data drives the view

The list has four rows because the array has four items. Add another animal to the array and the list gains another row — no extra view code needed. That's what "data-driven" means, and it's the foundation of almost every real app.

Download and run it

Open the Playgrounds file from GitHub, hit Run, and meet some animals.

← All apps in this book