UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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 {

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

Func checkValue() 
If _displayedValue.wrappedValue ==gameBrains.GetExpectedValue()
displayedValue = “"



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?




.onChange(of: displayedValue, perform: checkValue)


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 RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.