swiftui - 如何初始化@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 内部有一些逻辑也正在初始化,但认为它与此代码示例无关)
解决方案
这会奏效!也尝试清理你的构建文件夹并首先构建你的项目。
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 { }
推荐阅读
- ios - 在协议扩展中将 nil 传递给具有可选的一般约束参数的函数
- php - 随机打乱数组值
- angular - 该组件的名称是什么,如下图所示
- postgresql - postgres - 来自选择的内联变量赋值
- python - Updating the values of one column in a pandas dataframe based on input proportion
- java - 使用 java 将 jsonobjects 添加到 jsonarray 时避免重复
- angular - Angular:以后如何启动应用程序?
- java - 如何通过 Selenium Webdriver 向搜索字段发送文本?
- django - django 基于类的视图意外关键字参数
- jquery - GEB + jQuery:包含抛出 org.openqa.selenium.InvalidSelectorException