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

194

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

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

在 Xcode 7 和 Swift 2.0 中,我遇到了错误 二元运算符“|”不能应用于两个 UIUserNotificationType 操作数。请帮助我。


2
使用“()”括起来对我有效,UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: (UIUserNotificationType.Alert | UIUserNotificationType.Badge), categories: nil))。 - Nekak Kinich
1
现在我得到了这个错误信息:“找不到接受所提供参数的重载 '|'” - Nikita Zernov
我没有别的想法,抱歉。 - Nekak Kinich
4个回答

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

在 Swift 2 中,许多你通常需要这样做的类型已被更新为遵循 OptionSetType 协议。这使得它们可以像数组一样使用语法,而对于你的情况,你可以使用以下内容。

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

另外,如果你想检查一个选项集是否包含特定选项,现在不再需要使用按位与和空值检查。你可以像检查数组是否包含值一样,直接询问选项集是否包含特定值。

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
}

1
如果你有 flags |= .Alert?,那么你能使用 flags = [flags, .Alert] 吗? - user3246173
这个是否像一个集合一样处理,其中值是唯一的,还是像一个数组一样处理,可能会导致最终值不正确? - user3246173
@user3246173 这取决于flags变量的声明方式。如果flag的类型被明确声明为UIUserNotificationType,即 var flags: UIUserNotificationType = [.Alert, .Badge],那么它将被视为一个集合,你可以使用集合的实例方法如insert()union()unionInPlace()来添加元素,或者按照你提到的方法处理,而不必担心重复项。 - Mick MacCallum
如果您没有明确声明标志的类型为UIUserNotificationType,并且在声明中使用类似var flags = [UIUserNotificationType.Alert, UIUserNotificationType.Badge]的内容,则标志的类型将被推断为[UIUserNotificationType],并且通过append()或其他方法向其中添加元素将导致重复。对于后者,您可以简单地使用输入数组初始化UIUserNotificationType的实例,一切都会很好,但我建议采用基于集合的方法以获得更清晰的代码。 - Mick MacCallum

35
你可以写下以下内容:
let settings = UIUserNotificationType.Alert.union(UIUserNotificationType.Badge)

1
哇,这看起来真难看!NSTrackingAreaOptions.MouseEnteredAndExited.union(NSTrackingAreaOptions.MouseMoved).union(NSTrackingAreaOptions.ActiveAlways),但是感谢提供一个可行的解决方案。 - Chad Cache
2
如果我没记错的话,你可以写成 var options : NSTrackingAreaOptions =[.MouseEnteredAndExited,.MouseMo‌​ved,.ActiveAlways] - Bobj-C

7
我曾经做过的事情是:
//This worked
var settings = UIUserNotificationSettings(forTypes: UIUserNotificationType([.Alert, .Badge, .Sound]), categories: nil)

9
看起来几乎与上面接受的答案完全相同。考虑将其视为评论? - Max MacLeod

2

这在Swift 3中已经更新。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接