Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

@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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading