Efficiently accounting for different iOS versions

I one project, using .onChange(), I get an error: 'onChange(of:initial:_:)' is only available in iOS 17.0 or newer The solution provided is to wrap the code in if #available(iOS 17.0, *) { }, but I'm only able to wrap the whole view inside of it, like so:

if #available(iOS 17.0, *) {

    VStack () {
         // view with .onChange
    }

} else {
    VStack () {
         // view with older solution
    }
}

The view is quite lengthy so it would be very redundant to have the same view twice, (the same view for each component of the if/else statement). Is there a way to implement an if statement so that I would only need the code for the view once (something like the code below)?

VStack {

}
if #available(iOS 17.0, *) {
    .onChange() {

    }
} else {
    // older solution
}

Additionally, in a newer project, I don't have to include the if #available(iOS 17.0, *) { }, so I'm guessing the build is made for a newer iOS. If that's the case, would it not be compatible with older iOS versions? Any help would be greatly appreciated.

Hey,

.onChange() can be used before iOS 17. How exactly does your .onChang() look like?

I have not found a really good solution to this. For the time being, I just ignore the warning.

You may try to create your own modifier, where you would have the test for version.

https://www.hackingwithswift.com/books/ios-swiftui/custom-modifiers

 

Additionally, in a newer project, I don't have to include the if #available(iOS 17.0, *) { }, so I'm guessing the build is made for a newer iOS. If that's the case, would it not be compatible with older iOS versions?

It is not a question of new project. It is related to the minimum target you define.

Or you can set minimum target to iOS 17 (but not so good).

With this code I get the error:

.onChange(of: buttonState) { oldState, newState in

}

But not with this:

.onChange(of: buttonState) { state in

}

Would it be recommended to use a slightly older target so that more users would be able to access the app?

Efficiently accounting for different iOS versions
 
 
Q