Problem with If-statement

Hi all,
I have this code, and my goal is to check if the entered text in the textField is in the array. And if so set magicFroot to that word. But i keep getting this error, any ideas?

You can’t have code like self.magicFroot = self.searchTxt within a View like that; it has to be in a handler.

So something like this will work:

        HStack {
            TextField("Enter a Froot", text: $searchTxt)
                .onChange(of: searchTxt) { newTxt in
                    if array.contains(newTxt) {
                        magicFroot = newTxt
                    }
                }
        }

(BTW, if you are using Xcode 12, you don’t need those self. in there.)

Hi Thanks for the answer,
I tried the code, like following but got a couple of error


Btw im using XCode 11.7

That’s the problem then. onChange wasn’t available until Xcode 12.

You can do this instead:

TextField("Enter a Froot", text: self.$searchTxt) { isEditing in
    if array.contains(self.searchTxt) {
        self.magicFroot = self.searchTxt
    }
}

This solution uses the init(_:text:onEditingChanged:onCommit:) initializer of TextField but unfortunately means the change won’t be recognized until the user hits Enter.

If you absolutely need the checking to be done real-time, you can switch to using an @ObservableObject instead of a @State property. But that’s a little more complicated.

im not sure if you HStack is also in the right format, did you try to see that what error suggests for fixing?