Modifying SwiftData Object

Hi,

The dataModule in code below is a swiftData object being passed to the view and its property as key path but when trying to modify it I'm getting the error ."Cannot assign through subscript: 'self' is immutable" how to solve this issue ?

Kind Regards

struct ListSel<T: PersistentModel>: View {
    @Bindable var dataModule: T
    @Binding var txtValue: String
    
    var keyPath: WritableKeyPath<T, String>
    var turncate: CGFloat? = 94.0
    var image = ""
    
    var body: some View {
        HStack {
            Text(txtValue)
                .foregroundColor(sysSecondary)
                .font(.subheadline)
                .onChange(of: txtValue) { value in
                    dataModule[keyPath: keyPath] = value
                }
            Image(systemName: image)
                .foregroundColor(sysSecondary)
                .font(.subheadline)
                .imageScale(.small)
                .symbolRenderingMode(.hierarchical)
                .scaleEffect(0.8)
        }
        .frame(width: turncate, height: 20,  alignment: .leading)
        .truncationMode(.tail)
    }
}
Answered by Fat Xu in 813040022

change WritableKeyPath to ReferenceWritableKeyPath

https://fatbobman.com/en/posts/comprehensive-guide-to-mastering-keypath-in-swift/#writablekeypath-vs-referencewritablekeypath

Accepted Answer

change WritableKeyPath to ReferenceWritableKeyPath

https://fatbobman.com/en/posts/comprehensive-guide-to-mastering-keypath-in-swift/#writablekeypath-vs-referencewritablekeypath

[@Fat Xu](https://developer.apple.com/forums/profile/Fat Xu) Thanks allot that solved the problem

Modifying SwiftData Object
 
 
Q