Home > Software engineering >  Swift Update Struct in View
Swift Update Struct in View

Time:04-01

I apologize I am new to Swift and may be going about this completely wrong.

I am attempting to call the mutating function on my struct in my view to add additional phones or emails. This is my Struct.

struct CreateCustomer: Codable {
        var Phone: [CustomerPhone]
        var Emails: [String]
        init() {
            Phone = [CustomerPhone()]
            Emails = []
        }
        public mutating func addPhone(){
            Phone.append(CustomerPhone())
        }
        public mutating func addEmail(){
            Emails.append("")
        }
    }
struct CustomerPhone: Codable {
    var Phone: String
    var PhoneType: Int
    init(){
        Phone = ""
        PhoneType = 0
    }
}

I am attempting to add a phone to my state var with the following

Button("Add Phone"){
    $Customer_Create.addPhone()
}

I get the following Error

Cannot call value of non-function type 'Binding<() -> ()>' Dynamic key path member lookup cannot refer to instance method 'addPhone()'

Thank you for any help!

CodePudding user response:

If Customer_Create is a state property variable (like below) then you don't need binding, use property directly

struct ContentView: View {
  @State private var Customer_Create = CreateCustomer()

  var body: some View {
     Button("Add Phone"){
       Customer_Create.addPhone()    // << here !!
     }
  }
}

CodePudding user response:

You shouldn't be accessing the Binding via $, you should simply access the property itself.

Button("Add Phone"){
    Customer_Create.addPhone()
}

Unrelated to your question, but you should be conforming to the Swift naming convention, which is lowerCamelCase for variables and properties - so customerCreate, not Customer_Create.

  • Related