0
0
iOS Swiftmobile~20 mins

Identifiable protocol in iOS Swift - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Identifiable List Screen
This screen shows a list of simple items that conform to the Identifiable protocol. Each item has a unique id and a name. The list displays the names. This helps SwiftUI know which item is which when updating the list.
Target UI
---------------------
| Identifiable List |
---------------------
| * Item 1          |
| * Item 2          |
| * Item 3          |
---------------------
Create a struct named Item that conforms to Identifiable.
Give Item a unique id property of type UUID.
Give Item a name property of type String.
Create a SwiftUI List that shows the names of several Item instances.
Use the id property automatically for the List to identify each row.
Starter Code
iOS Swift
import SwiftUI

struct Item: Identifiable {
    // TODO: Add id and name properties
}

struct IdentifiableListView: View {
    let items = [
        // TODO: Create some Item instances
    ]

    var body: some View {
        NavigationView {
            List {
                // TODO: Show item names here
            }
            .navigationTitle("Identifiable List")
        }
    }
}

struct IdentifiableListView_Previews: PreviewProvider {
    static var previews: some View {
        IdentifiableListView()
    }
}
Task 1
Task 2
Task 3
Task 4
Solution
iOS Swift
import SwiftUI

struct Item: Identifiable {
    let id = UUID()
    let name: String
}

struct IdentifiableListView: View {
    let items = [
        Item(name: "Item 1"),
        Item(name: "Item 2"),
        Item(name: "Item 3")
    ]

    var body: some View {
        NavigationView {
            List(items) { item in
                Text(item.name)
            }
            .navigationTitle("Identifiable List")
        }
    }
}

struct IdentifiableListView_Previews: PreviewProvider {
    static var previews: some View {
        IdentifiableListView()
    }
}

We created a struct Item that conforms to Identifiable. This means each item must have a unique id. We used UUID() to generate a unique id automatically. The name property holds the text to show.

In the view, we made a list of Item objects. The SwiftUI List uses the id property to track each row uniquely. This helps SwiftUI update the list efficiently when data changes.

The UI shows a simple list with the item names and a navigation title.

Final Result
Completed Screen
---------------------
| Identifiable List |
---------------------
| * Item 1          |
| * Item 2          |
| * Item 3          |
---------------------
User can scroll the list if it grows longer.
Each row shows the item name.
SwiftUI uses the id to keep track of each item for smooth updates.
Stretch Goal
Add the ability to delete items from the list by swiping left on a row.
💡 Hint
Use the .onDelete modifier on the List and make the items array @State to allow changes.