Swift 2 修改了许多通常这样使用的类型,让它们改为实现 OptionSetType 协议。因此它们支持类似数组的语法,你的这个例子可以写成下面这样。
let notificationOptions = UIUserNotificationSettings(forTypes: [.Alert, .Badge], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationOptions)
另外,检查一个选项是否属于某个选项集时,也不再需要先做按位 AND 再检查 nil。可以直接询问选项集是否包含这个值,就像检查数组中有没有某个元素一样。
let notificationOptions = UIUserNotificationSettings(forTypes: [.Alert, .Badge], categories: nil)
if notificationOptions.types.contains(.Alert) {
// handle this option
}
在 Swift 3 中,这些例子应当这样写。
let notificationOptions = UIUserNotificationSettings(types: [.alert, .badge], categories: nil)
UIApplication.shared.registerUserNotificationSettings(notificationOptions)
以及
let notificationOptions = UIUserNotificationSettings(types: [.alert, .badge], categories: nil)
if notificationOptions.types.contains(.alert) {
// handle this option
}
从英语翻译·查看原文Swift 2 changed many of the types commonly used this way to implement the OptionSetType protocol instead. Consequently they support a syntax resembling arrays, so your particular example can be written like this.
let notificationOptions = UIUserNotificationSettings(forTypes: [.Alert, .Badge], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationOptions)
Relatedly, checking whether an option belongs to an option set no longer requires a bitwise AND followed by testing for nil. Instead, ask whether that set contains the particular value, much as you would check an array for an element.
let notificationOptions = UIUserNotificationSettings(forTypes: [.Alert, .Badge], categories: nil)
if notificationOptions.types.contains(.Alert) {
// handle this option
}
For Swift 3, write those examples this way:
let notificationOptions = UIUserNotificationSettings(types: [.alert, .badge], categories: nil)
UIApplication.shared.registerUserNotificationSettings(notificationOptions)
and
let notificationOptions = UIUserNotificationSettings(types: [.alert, .badge], categories: nil)
if notificationOptions.types.contains(.alert) {
// handle this option
}