Swift 更新视图中的结构

Swift Update Struct in View

很抱歉,我是 Swift 的新手,可能完全错了。

我试图在我的视图中调用我的结构上的变异函数来添加额外的 phones 或电子邮件。这是我的结构。

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
    }
}

我正在尝试使用以下

向我的状态变量添加 phone
Button("Add Phone"){
    $Customer_Create.addPhone()
}

我收到以下错误

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

感谢您的帮助!

如果Customer_Create是一个状态属性变量(如下)那么你不需要绑定,直接使用属性

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

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

您不应该通过 $ 访问 Binding,您应该直接访问 属性 本身。

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

与您的问题无关,但您应该遵守 Swift 命名约定,即变量和属性的 lowerCamelCase - 所以 customerCreate,而不是 Customer_Create.