【发布时间】:2023-01-12 04:33:29
【问题描述】:
我在添加 focusField: Binding<Bool> 属性时出现此错误“在初始化所有存储的属性之前使用了‘self’”,它在发生错误的代码上突出显示并有注释,我不明白为什么这正在发生。
这与下面的代码sn-p有关:
struct TextInputField: View {
final class Model: ObservableObject {
// MARK: Properties
@Published var text: String = ""
var placeholder: String = ""
var currentValue: String = ""
var cancellables: Set<AnyCancellable> = Set<AnyCancellable>()
// MARK: Initialization
init() {
self.$text
.sink(receiveValue: { value in
self.currentValue = value
})
.store(in: &cancellables)
}
}
// MARK: Properties
private let textFieldPublisher = PassthroughSubject<(String?, TextInputErrorState), Never>()
private let output: PassthroughSubject<(name: String?, error: TextInputErrorState), Never>
private let textInputType: TextInputType
@State private var cancellable = Set<AnyCancellable>()
@State private var inputErrorState: TextInputErrorState = .none
@State private var isAnimated = false
@State private var textBinding: String = ""
private var isEditable: Bool = true
@FocusState private var isFocused: Bool
@ObservedObject var model: TextInputField.Model = TextInputField.Model()
@Binding private var focusField: Bool
// MARK: Initialization
init(title: String,
output: PassthroughSubject<(name: String?, error: TextInputErrorState), Never>, inputType: TextInputType = .firstName,
currentValue: String = "" ,
preValue: String = "",
isEditable: Bool = true,
focusField: Binding<Bool>) {
self.textInputType = inputType
self.output = output
model.placeholder = title // <- 'self' used before all stored properties are initialized
if !preValue.isEmpty {
model.text = preValue // <- 'self' used before all stored properties are initialized
}
if !currentValue.isEmpty {
model.text = currentValue // <- 'self' used before all stored properties are initialized
}
self._focusField = focusField
self.isEditable = isEditable
}
【问题讨论】:
-
在初始化
self上的所有属性(例如focusField)之前,您正在操作self上的某些东西(具体来说,首先是model) -
不相关,但您的 Combine 代码中存在漏洞——您应该在
sink中使用[weak self]