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

标签 ios swift swift2

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

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

在 Xcode 7 和 Swift 2.0 中 - 我收到错误 Binary Operator "|"不能应用于两个 UIUserNotificationType 操作数。请帮助我。

最佳答案

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

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
}

Swift 3中,示例必须写成如下:

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
}

关于ios - Swift 2.0 - 二元运算符 "|"不能应用于两个 UIUserNotificationType 操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30761996/

相关文章:

ios - 在完成 block Swift 中返回

swift - Inception V3 CoreML 输出标签翻译语言

ios - 将 Core Data 对象从 DetailViewController 传递到另一个 View Controller

ios - 将变量 (Int) 传递给 View 控件 (Popover)

ios - 使用 swift 2.0 更改 XCODE 7 中 UITabBar 和 UITabBarItems 的文本和图标颜色?

objective-c - 即时更改表格 View 行高

ios - 在iphone/ipad上自由手绘

ios - 使用表格数据进行 CoreML 设备端模型训练

ios - 在 UIAlertController 之后重新加载 View

iphone - 将 UIPicker 添加到文本字段