High quality code follows several principles. One would be the Single Responsible Principle, that states that a class should have only one responsibility, or — as Uncle Bob says — there should be just one reason for a class to change.
Another principle is the Dependency Inversion Principle: A class should not depend on lower level classes, but on abstractions (protocols) that these lower level classes implements. This also means that all dependences must be passed into the class that uses them.
Applied on your question one solution could be:
- A view controller has a datasource property that is defined as a protocol.
- Several classes implement this protocol, each for different iOS versions.
- A class exists which only preps is to select the right version. This version selection can be done in many ways, I stick with
#available
The datasource protocol:
protocol ViewControllerDataSourcing: class {
var text:String { get }
}
and it's implementations:
class ViewControllerDataSourceIOS10: ViewControllerDataSourcing {
var text: String {
return "This is iOS 10"
}
}
class ViewControllerDataSourceIOS11: ViewControllerDataSourcing {
var text: String {
return "This is iOS 11"
}
}
class ViewControllerDataSourceIOSUnknown: ViewControllerDataSourcing {
var text: String {
return "This is iOS Unknown"
}
}
The class that selects the right version class:
class DataSourceSelector{
class func dataSource() -> ViewControllerDataSourcing {
if #available(iOS 11, *) {
return ViewControllerDataSourceIOS11()
}
if #available(iOS 10, *) {
return ViewControllerDataSourceIOS10()
}
return ViewControllerDataSourceIOSUnknown()
}
}
and finally the view controller
class ViewController: UIViewController {
var dataSource: ViewControllerDataSourcing?
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = DataSourceSelector.dataSource()
label.text = dataSource?.text
}
}
This is a very simple example that should highlight the different components in charge.
#available
has no converse. For example, you can include stuff if this is iOS 11 but you can't exclude stuff if this is iOS 11. – Woothenelse
block after yourif
block. – Shrug@available
, not#available
. – Shrug