NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

SOLVED: How does one functionally check a condition and set a related value inside an .onChang() block?

Forums > SwiftUI

I’m having trouble trying to run a function whenever a State-wrapped string is changed. Basically, whenever this string is changed, I need to check if the value matches a possible answer.

Because this property is wrapped with @State, property observers don’t work for triggering the desired function whenever the string is updated.

Pressing the button under the Text View successfully updates the Text View, but I can’t actually call checkValue() using the .onChange modifier on the Text view because I get this error:

“Cannot convert value of type ’some View’ to expected argument type ’Text’.”

Struct ContentView: View {

@State private var displayedValue = “”
/*Just a class that handles data shared between different views and  functions for managing game state*/
@StateObject gameBrains = GameBrains()

Var body -> some View {

Text(displayedValue)
.onChange(of: displayedValue, perform: checkValue())
Button(“Update Display Value”) {
//code that adds to the displayedValue property
}//button
}//body

Func checkValue() 
If _displayedValue.wrappedValue ==gameBrains.GetExpectedValue()
GameBrains.triggerWin()
displayedValue = “"
}//conditional
}//struct

   

@Bnerd  

If I am not wrong..try the bellow

.onChange(of: displayedValue, action: checkValue)

   

That doesn't work either. It actually throws an error saying that 'perform:' was expected, rather than 'action:'. Any other ideas?

   

@Bnerd  

this?

.onChange(of: displayedValue, perform: checkValue)

1      

You need to wrap the Text and Button in some kind of container, like a VStack.

The body property of a View struct is a ViewBuilder, which needs to return a single value. So you always need one outer element—like a VStack, HStack, List, etc—that can contain everything else that you want to appear in the body.

Also, @Bnerd's second suggestion is correct. You aren't calling the checkValue function but merely passing in a reference to that function, so don't add the parentheses in the perform parameter:

.onChange(of: displayedValue, perform: checkValue)

   

Thank you both for the help. I really appreciate it.

   

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.