BLACK FRIDAY SALE: Save big on all my Swift books and bundles! >>

How to create a List or a ForEach from a binding

Paul Hudson    @twostraws   

Updated for Xcode 14.1

New in iOS 15

SwiftUI lets us create a List or ForEach directly from a binding, which then provides the content closure with individual bindings to each element in the collection of data we’re showing. This is important for the times when the content you’re showing for each item needs a binding to some of its data, such as list rows having a text field to edit a user’s name.

To use this, pass the binding into your list directly, e.g. $users, then accept a binding in the content closure, e.g. $user. For example, in this code we show a list of users and add to each row a Toggle determining whether they have been contacted or not:

struct User: Identifiable {
    let id = UUID()
    var name: String
    var isContacted = false
}

struct ContentView: View {
    @State private var users = [
        User(name: "Taylor"),
        User(name: "Justin"),
        User(name: "Adele")
    ]

    var body: some View {
        List($users) { $user in
            Text(user.name)
            Spacer()
            Toggle("User has been contacted", isOn: $user.isContacted)
                .labelsHidden()
        }
    }
}

Download this as an Xcode project

Using a binding in this way is the most efficient way of modifying the list, because it won’t cause the entire view to reload when only a single item changes.

Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI 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 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 Beyond Code

Was this page useful? Let us know!

Average rating: 3.6/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.