Home > Software design >  'self' used before all stored properties are initialized error with Model in View
'self' used before all stored properties are initialized error with Model in View

Time:01-11

I have this error "'self' used before all stored properties are initialized", its happening when I'm adding a focusField: Binding<Bool> property, It's highlighted on the code where the error is occurring has a comment, I can't figure why this is happening.

This is related to the following code snippet:

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
    }

CodePudding user response:

move self._focusField = focusField to just after self.output = output in your init(title: String, output: ....). The reason for the error is given to you by the error message.

Note your TextInputField is missing the required View body

  • Related