Swift 2.0 - 二元运算符“|”不能应用于两个 UIUserNotificationType 操作数

Swift 2.0 - Binary Operator "|" cannot be applied to two UIUserNotificationType operands

我正在尝试通过这种方式注册我的本地通知应用程序:

UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil))

在 Xcode 7 和 Swift 2.0 中 - 我收到错误 Binary Operator "|" cannot be applied to two UIUserNotificationType operands。请帮助我。

在 Swift 2 中,您通常会对其执行此操作的许多类型已更新为符合 OptionSetType 协议。这允许使用类似数组的语法,在您的情况下,您可以使用以下内容。

let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)

并且在相关说明中,如果要检查选项集是否包含特定选项,则不再需要使用按位与和 nil 检查。您可以简单地询问选项集是否包含特定值,就像检查数组是否包含值一样。

let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge], categories: nil)

if settings.types.contains(.Alert) {
    // stuff
}

Swift3中,样本必须写成如下:

let settings = UIUserNotificationSettings(types: [.alert, .badge], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)

let settings = UIUserNotificationSettings(types: [.alert, .badge], categories: nil)

if settings.types.contains(.alert) {
    // stuff
}

你可以这样写:

let settings = UIUserNotificationType.Alert.union(UIUserNotificationType.Badge)

对我有用的是

//This worked
var settings = UIUserNotificationSettings(forTypes: UIUserNotificationType([.Alert, .Badge, .Sound]), categories: nil)

这已在 Swift 3 中更新。

        let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        UIApplication.shared.registerUserNotificationSettings(settings)