Updated for Xcode 14.2
In order to handle dynamic items, you must first tell SwiftUI how it can identify which item is which. This is can either be done by specifying the identifying property by hand, or by using the Identifiable
protocol. This protocol has only one requirement, which is that the type must have some sort of id
value SwiftUI can use to see which item is which.
To demonstrate this, we can create three things then put them together:
Restaurant
struct that says restaurants have an ID and name, with the ID being a random identifier just so that SwiftUI knows which is which.RestaurantRow
view that stores one restaurant and prints its name in a text view.Here’s all that in code:
// A struct to store exactly one restaurant's data.
struct Restaurant: Identifiable {
let id = UUID()
let name: String
}
// A view that shows the data for one Restaurant.
struct RestaurantRow: View {
var restaurant: Restaurant
var body: some View {
Text("Come and eat at \(restaurant.name)")
}
}
// Create three restaurants, then show them in a list.
struct ContentView: View {
let restaurants = [
Restaurant(name: "Joe's Original"),
Restaurant(name: "The Real Joe's Original"),
Restaurant(name: "Original Joe's")
]
var body: some View {
List(restaurants) { restaurant in
RestaurantRow(restaurant: restaurant)
}
}
}
Download this as an Xcode project
Most of that is just creating data – the last part is where the real action is: using List(restaurants)
creates a list from the restaurants
array, executing the following closure once for every item in the array. Each time the closure goes around the restaurant
input will be filled with one item from the array, so we use that to create a RestaurantRow
.
In fact, in trivial cases like this one we can make the code even shorter: List(restaurants, rowContent: RestaurantRow.init)
does exactly the same thing.
SPONSORED Build a functional Twitter clone using APIs and SwiftUI with Stream's 7-part tutorial series. In just four days, learn how to create your own Twitter using Stream Chat, Algolia, 100ms, Mux, and RevenueCat.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.