‘onChange(of:perform:)’ was deprecated in iOS 17.0: Use `onChange` with a two or zero parameter action closure instead.

Previously, we could use a single parameter in onChange() in SwiftUI. But now we can do that, but it will show us a warning: 'onChange(of:perform:)' was deprecated in iOS 17.0: Use `onChange` with a two or zero parameter action closure instead.

I was following a tutorial yesterday and encountered this issue. So I think it will be worth sharing the solution of this warning.

This is the coding part where I faced this warning:

.onChange(of: state){ myValue in
            switch myValue {
            case.inactive:
                print("I am inactive")
                
           // rest of your cases or codes goes here
            
            case.background:
                print("I am in background")
            @unknown default: print("Default")
            }

For this warning, there is no fix now button in Xcode, but it is clearly written that we have to use no parameter or two parameters to avoid this warning. But in my case, I must have to use a parameter of: so I added an extra parameter just like this.

Solution:

Just modified the first line like this:

.onChange(of: state, initial: true){ initial, myValue in

This removed the warning.

If you wish you can remove initial: true. It will work fine.

You can also remove myValue into make it a zero parameter.

Now the choice is yours on how you would like to fix it.

You can also check Check if SwiftUI app is running in background where I have used onChange working nice in the latest iOS versions. Tested on iOS 17+

Leave a Reply

Your email address will not be published. Required fields are marked *