I want to use a feature that is only available in >= iOS 16 therfore I use the @available flag but it does not work because "Stored properties cannot be marked potentially unavailable with '@available'"
@available(iOS 16.0, *) @State private var photoPickerItems = [PhotosPickerItem]()
That makes sense, and is expected. The memory map of the object’s properties gets defined at compile-time. The compiler wants all instances of your class to contain a fixed set of properties so it knows where to find the properties in memory.
If you want properties to be available or not depending on the OS version, make those properties Optional
and then write instance method code that uses an @available
to either load a value into each property if the OS is available, or leave it nil if not.
Instead of declaring it as:
@available(iOS 16.0, *) @State private var photoPickerItems = [PhotosPickerItem]()
Which doesn't work, declare it as
@State private var photoPickerItems: [PhotosPickerItem]? = nil
And then in your initializer, wrap an assignment to that property in an @available. That way, except in iOS ≥ 16, the property will remain nil. In iOS ≥ 16, the @available statement will execute and your property will get a value assigned to it.
(You will then need to rewrite all the code that reads that property to unwrap it, use if let
, guard let
, the nil coalescing operator, or other ways of dealing with optionals. (Explaining all those is beyond the scope of this answer, and such "nuts and bolts" Swift that if you don't know how to deal with optionals, you should stop and study the subject until you do.)