搞事情

Swift 代码适配不同系统版本的判断方式

2018-10-24  本文已影响60人  飞天喵咪

在代码中检查不同的swift版本

#if swift(>=3.0)
func foo(with array: [Any]) {
    print("Swift 3 implementation")
}
#else
func foo(with array: [AnyObject]) {
    print("Swift 2 implementation")
}
#endif

在方法中根据不同的系统版本,处理对应的逻辑

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)
    }
}

在方法外根据不同的系统版本,处理对应的逻辑。(最小支持版本,最大支持版本)

// 这里支持的系统版本是 大于等于 9.0 小于11.0
@available(iOS, introduced: 9.0, deprecated: 11.0)
func someMethod() {
    // this is only supported iOS 9 and 10
}

在方法外根据不同的系统版本,处理对应的逻辑。(最小支持版本)

// 这里支持的系统版本是 大于等于 10.0 之后的所有版本
@available(iOS 10.0, *)
func someMethod() {
    // this is only available in iOS 10 and later
}
上一篇下一篇

猜你喜欢

热点阅读