UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Updating array item in a List

Forums > SwiftUI

How do I update a single array item that's being displayed in a List with a ForEach loop?

I have my list, and a ForEach that itterates over my array of custom items. Inside the ForEach I have a button, and that button should update the specific array item that's being shown on that line.

Here's my current code, it throws an error on the line item.LastTouch = Date.now: "Cannot assign to property: 'item' is a 'let' constant"

            List {
                ForEach(contacts.items) { item in
                    HStack{
                        VStack(alignment: .leading){
                            Text(item.name)
                            Text(item.company)
                            Text(item.lastTouch.description)
                        }
                        Spacer()

                        Button(action: {
                            item.lastTouch = Date.now
                            //print(item.lastTouch)
                            //contacts.sort()
                        }) {
                            Image(systemName: "checkmark.seal.fill")
                                .resizable()
                                .frame(width: 50,height: 50)
                        }
                        .buttonStyle(PlainButtonStyle())
                    }
                }
                .onDelete(perform: removeItems)
            }

2      

If your contacts.items comes from an ObservedObject or a StateObject, you can use a binding to the individual items in your array:

ForEach($contacts.items) { $item in
   ...
}

2      

Change your item properties from 'let' to 'var' and you will then be able to modify them.

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.