Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use different implementations of a class depending on iOS version?

iOS 11 recently added a new feature I would like to use but I still need to support older versions of iOS. Is there a way to write the same class twice and have newer versions of iOS use one version of the class and older versions of iOS use the other?

(Note: Originally I used if #available(iOS 11, *) but I had to use it in so many places that I thought it would just be cleaner to have 2 versions of the class if possible. Maybe there's a way of using @availble somehow? I was focused on using @available rather than pre-compiler #IFDEF stuff because it seems like the "available" tags are the preferred way to do it in Swift now?)

like image 847
TenaciousJay Avatar asked Jan 03 '23 12:01

TenaciousJay


1 Answers

protocol Wrapper {

}

extension Wrapper {
    static func instantiate(parametersAB: Any*) -> Wrapper{
        if #available(iOS 11.0, *) {
            return A(parametersA)
        } else {
            return B(parametersB)
        }
    }
}

@available(iOS 11.0,*)
class A: Wrapper {
    //Use new feature of iOS 11
    init(parametersA: Any*) {
      ...
    }
}

class B: Wrapper {
    //Fallback
    init(parametersB: Any*) {
      ...
    }
}

Now you get your instance by calling Wrapper.instationate(params) and with this you forget about the check in the rest of the code, and uses the new feature if it possible.

This solution is only possible if you can establish the same interface for both classes (even if it is a dummy version of the method).

like image 78
hfehrmann Avatar answered Mar 02 '23 01:03

hfehrmann