In many apps, you'd often want to support the newest 2 major iOS versions (or more).
In the earlier days, in Obj-C, you could check directly — using NSProcessInfo
— the iOS version number and see which features are available. Then Apple recommended for us to check directly if a feature is available by checking if a class or an object responds to specific selectors instead of checking iOS version numbers.
With Swift, the official recommendation switches back to checking iOS version numbers again with the use of #available
. Not only can you use #available
to check against iOS version numbers at runtime in Swift, you can apply the @available
attribute to Swift functions and methods to indicate the minimum iOS version it requires. e.g.
@available(iOS 9, *)
func functionThatRequiresiOS9() {
if #available(iOS 10, *) {
functionThatRequiresiOS10()
}
}
There are other uses of @available
, for example in Swift 3.1, the @available
attribute has been expanded to support Swift language versions. This is useful primarily for library authors:
@available(swift, obsoleted: 3.1)
func functionThatIsObsoleteIn3Dot1andLater() {
}
PS: everything above applies to watchOS, tvOS and macOS too.
Your feedback is valuable: Do you want more nuggets like this? Yes or No
.
.