NEW: Join my free 100 Days of SwiftUI challenge today! >>

How to create a list of dynamic items

Paul Hudson    @twostraws   

Fully updated for Xcode 11.2

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)

SAVE 20% ON iOS CONF SG The largest iOS conference in Southeast Asia is back in Singapore for the 5th time in January 2020, now with two days of workshops plus two days of talks on SwiftUI, Combine, GraphQL, and more! Save a massive 20% on your tickets by clicking on this link.

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.6/5