【问题标题】:'self' used before all stored properties are initialized error with Model in View\'self\' 在所有存储的属性初始化错误之前使用视图中的模型
【发布时间】: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]

标签: ios swift swiftui combine


【解决方案1】:

在你的init(title: String, output: ....)中将self._focusField = focusField移动到self.output = output之后。错误原因由错误消息提供给您。

请注意,您的TextInputField 缺少所需的视图正文

【讨论】:

  • 谢谢,解决了这个问题,英语不是我的母语,所以有时我很难理解这些消息。
  • 好点,我会尽量让我的答案/cmets 在未来更容易理解。
猜你喜欢
  • 1970-01-01
  • 2016-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-09
  • 1970-01-01
相关资源
最近更新 更多