首页 > 解决方案 > 如何初始化@Binding 数组

问题描述

所以我正在做一些重构,我遇到了我想要重构的这行代码:

struct MyView: View {
     @State private var myArrayOfCustomObjects = [CustomObject]
     let text: String
          var body: some View {
             Text(text)
          }
}

然后当我想重构视图时..

struct ExtractedView: View {
  @Binding var customObjects: [CustomObject]
  let text: String

  init(customObjects: Binding<Array<CustomObject>>, text: String) {
    self.customObjects = customObjects  // Error: 'self' used before all stored properties are initialized

        // Also tried _customObjects = customObjects
    self.text = text

  }
     var body: some View {
          
        Text(text)
     }
}

这段代码当然被简化了,但我担心我可能会因为一些复杂性而收到错误,因为我没有在示例中公开。欢迎任何反馈

我究竟做错了什么??

(我还有一个Environment实例(managedObjectContext)和一个 coreData 类 - 它在 init 内部有一些逻辑也正在初始化,但认为它与此代码示例无关)

标签: swiftui

解决方案


这会奏效!也尝试清理你的构建文件夹并首先构建你的项目。

struct ExtractedView: View {
  @Binding var customObjects: [CustomObject]
  let text: String

  init(customObjects: Binding<Array<CustomObject>>, text: String) {
    self._customObjects = customObjects

    self.text = text

  }
     var body: some View {
          
        Text(text)
     }
}


struct CustomObject { }

推荐阅读