swiftuicontactpicker

Cannot assign through dynamic lookup property: is immutable when using @Binding


I am trying to use the ContactPicker from SwiftUIKit Package (github.com/youjinp/SwiftUIKit). It has been great in the past, but now that I am trying to restructure my app to correctly use NavigationStack and @Bindable I am getting the following errors when I try to assign their chosen Contact in the picker. First the code,

            ContactPicker(showPicker: $showPicker, onSelectContact: {contact in
                $recipient.firstName = contact.givenName
                $recipient.lastName = contact.familyName
                if contact.postalAddresses.count > 0 {
                    if let addressString = (
                        ((contact.postalAddresses[0] as AnyObject).value(forKey: "labelValuePair")
                         as AnyObject).value(forKey: "value"))
                        as? CNPostalAddress {
                        let mailAddress =
                            CNPostalAddressFormatter.string(from: addressString, style: .mailingAddress)
                        $recipient.addressLine1 = "\(addressString.street)"
                        $recipient.addressLine2 = ""
                        $recipient.city = "\(addressString.city)"
                        $recipient.state = "\(addressString.state)"
                        $recipient.zip = "\(addressString.postalCode)"
                        $recipient.country = "\(addressString.country)"
                        print("Mail address is \n\(mailAddress)")
                    }
                } else {
                    $recipient.addressLine1 = "No Address Provided"
                    $recipient.addressLine2 = ""
                    $recipient.city = ""
                    $recipient.state = ""
                    $recipient.zip = ""
                    $recipient.country = ""
                    print("No Address Provided")
                }
                self.showPicker.toggle()
            }, onCancel: nil)

All instances of $recipient. have the following two errors:

Cannot assign through dynamic lookup property: '$recipient' is immutable

Cannot assign value of type 'String' to type 'Binding'

Recipient is defined as @Bindable var recipient: Recipient

I am not sure how to approach this. If only Apple had a SwiftUI version of the ContactPicker I probably wouldn't have this issue.


Solution

  • From your previous post, I see you are using SwiftData and @Query private var recipients: [Recipient] in your parent view.

    In that case, you could try adding @Bindable var recipient: Recipient in your child view (the view with ContactPicker) and remove the $ in ContactPicker(...), such as:

     ContactPicker(showPicker: $showPicker, onSelectContact: {contact in
         recipient.firstName = contact.givenName  // <--- here
         // ....