NEW: Get your ticket for Hacking with Swift Live 2019! >>

< How to create a list of static items   How to let users delete rows from a list >

How to create a list of dynamic items

In order to handle dynamic items, you must first tell SwiftUI how it can identify which item is which. This is done using the Identifiable protocol, which has only one requirement: some sort of id value that SwiftUI can use to see which item is which.

For example, you might create a 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:

struct Restaurant: Identifiable {
    var id = UUID()
    var name: String
}

Next you would define what a list row looks like. In our case we’re going to define a RestaurantRow view that stores one restaurant and prints its name in a text view:

struct RestaurantRow: View {
    var restaurant: Restaurant

    var body: some View {
        Text("Come and eat at \(restaurant.name)")
    }
}

Finally we can create a list view that shows them all. This means creating some example data, putting it into an array, then passing that into a list to be rendered:

struct ContentView: View {
    var body: some View {
        let first = Restaurant(name: "Joe's Original")
        let second = Restaurant(name: "The Real Joe's Original")
        let third = Restaurant(name: "Original Joe's")
        let restaurants = [first, second, third]

        return List(restaurants) { restaurant in
            RestaurantRow(restaurant: restaurant)
        }
    }
}

Most of that is just creating data – the last part is where the real action is:

return List(restaurants) { restaurant in
    RestaurantRow(restaurant: restaurant)
}

That creates a list from the restaurants array, executing the 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:

return List(restaurants, rowContent: RestaurantRow.init)

HACKING WITH SWIFT LIVE This July is a new two-day event where you'll be inspired by great speakers on day one then learn all the amazing new features from WWDC on day two – click here for more information and tickets.

< How to create a list of static items   How to let users delete rows from a list >
MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 5.0/5

Click here to visit the Hacking with Swift store >>