TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

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.