Identifiable Items
Part of the Introduction to SwiftUI section of Coddy's Swift journey. Lesson 30 of 50.
Real lists hold structs, and two items can share a name. Give each item its own identity by making the struct Identifiable: it needs an id property that is different for every item.
struct Book: Identifiable {
let id = UUID()
let title: String
let author: String
}UUID() makes a new random, unique value each time a Book is created. With Identifiable items, ForEach needs no id: argument:
ForEach(books) { book in
VStack(alignment: .leading) {
Text(book.title)
.font(.headline)
Text(book.author)
}
}Challenge
EasyBook is almost ready for ForEach. Make it conform to Identifiable by adding a let id = UUID() property, then show every book's title with ForEach(books) inside the VStack.
Try it yourself
import SwiftUI
@main
struct CoddyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction to SwiftUI
Practice on your own: Swift playground