'Swift Update Struct in View
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!
Solution 1:[1]
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 !!
}
}
}
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Asperi |
| Solution 2 | Dávid Pásztor |
