@Bindning wrapper gives an error while using with init()

I am creating a special Textfield for macOS. I want to create my own initializer, for special naming. But when I create that initializer with @Binding it gives two errors.

I don’t now why it gives this initialization error. It’s being clearly initialized there. Here is my code:

struct MacOSTextField: View{
    @Binding var text: String
    var displayText: String
    var body: some View{
        RoundedRectangle(cornerRadius: 0.4)
            .overlay {
                TextField(displayText, text: $text)
            }
    }
    init(text: String, displayText: String) {
        self.displayText = displayText
        self.text = text << Error: 'self' used before all stored properties are initialized
    } << Error: Return from initializer without initializing all stored properties
}

It does not work when I remove self.text = text or change the place of it. Here is the code when self.text = text is removed:

struct MacOSTextField: View{
    @Binding var text: String
    var displayText: String
    var body: some View{
        RoundedRectangle(cornerRadius: 0.4)
            .overlay {
                TextField(displayText, text: $text)
            }
    }
    init(text: String, displayText: String) {
        self.displayText = displayText
        self.text = text
    } << Error: Return from initializer without initializing all stored properties

Any help will be appreciated.

>Solution :

Since text is a @Binding, you need to pass it as such to the init:

init(
    text: Binding<String>, // <-- passing it to the init
    displayText: String
) {
        self.displayText = displayText
        self._text = text // <-- assigning value to it. Notice the "_"
    }

This of course assumes that the view that holds this view will have something like:

struct ParentView: View {
    
    @State var text: String = ""
    
    var body: some View {
        MacOSTextField(
            text: $text, // <-- passing a binded variable. Notice the "$" 
            displayText: "Something"
        )

Also note that what you call displayText is actually a placeholder text. the "displayed text" will be in the text binded variable

Leave a Reply