Available check in Class

Viewed 39

I was trying to use PhotosPicker() in my practice project, and use #available/@availabvle to check the IOS version. I did some research, but haven't found a way to solve this issue.

class PostAndCollectionVM: ObservableObject {
    
    @Published var houseCollection = [RoomPostDM]()
    @Published var providerCollection = [RoomPostDM]()
    @Published var roomData: RoomPostDM = .empty
    
    if #available(iOS 16, *) {
        @Published var selectedImage: PhotosPickerItem? = nil
    } else {
        @Published var selectedImage = UIImage()
    }
}

Could I use #available directly in class without func or Compute property to wrap it, or could I need to use @available for the different classes like so?

@available(ios 16, *) class collectionVM {}

@available(ios, obsoleted: 15, *) clas class collectionVM2 {}
1 Answers

This can be done, but with the following restrictions/changes:

  1. You cannot use the same variable name

  2. You will need to setup the variable within an availability if statement

    class Test: ObservableObject {
    
    @available(iOS 13, *)
    @Published var x: String? = nil
    
    @available(iOS 14, *)
    @Published var y: String? = nil
    
    init()
    {
        if #available(iOS 14, *)
        {
            self.y = "iOS 14"
        }
        else
        {
            // 'y' is only available in application extensions for iOS 14 or newer
            self.y = "iOS 13"
        }
    }
    

    }

Related