What is the Swift syntax for:
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000
//...
#endif
There's no direct analog of the #if
compile-time directive for max OS version, but depending upon the broader objective, there are a few techniques you can avail yourself of:
There is a #if
directive in Swift for language version (but not OS versions). See "Conditional Compilation Block" section of The Swift Programming Language: Language Reference: Statements. For example:
#if swift(>=3.0)
func foo(with array: [Any]) {
print("Swift 3 implementation")
}
#else
func foo(with array: [AnyObject]) {
print("Swift 2 implementation")
}
#endif
You can perform #available
runtime check for OS versions. See "Checking API Availability section of The Swift Programming Language: Control Flow. For example, UserNotifications framework is available effective iOS 10, so you'd do something like:
private func registerForLocalNotifications() {
if #available(iOS 10, *) {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { granted, error in
guard granted && error == nil else {
// display error
print(error?.localizedDescription ?? "Unknown error")
return
}
}
} else {
let types: UIUserNotificationType = [.badge, .sound, .alert]
let settings = UIUserNotificationSettings(types: types, categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
}
}
If you have an API that is only available in certain OS versions, you can use @available
directive. See "Declaration Attributes" discussion in The Swift Programming Language: Language Reference: Attributes for more information. For example:
@available(iOS, introduced: 9.0, deprecated: 11.0)
func someMethod() {
// this is only supported iOS 9 and 10
}
or,
@available(iOS 10.0, *)
func someMethod() {
// this is only available in iOS 10 and later
}