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

Nik*_*nov 191 ios swift swift2

我试图以这种方式注册本地通知的应用程序:

UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil))
Run Code Online (Sandbox Code Playgroud)

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

Mic*_*lum 387

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

let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
Run Code Online (Sandbox Code Playgroud)

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

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

if settings.types.contains(.Alert) {
    // stuff
}
Run Code Online (Sandbox Code Playgroud)

Swift 3中,样本必须写成如下:

let settings = UIUserNotificationSettings(types: [.alert, .badge], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
Run Code Online (Sandbox Code Playgroud)

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

if settings.types.contains(.alert) {
    // stuff
}
Run Code Online (Sandbox Code Playgroud)


Bob*_*j-C 35

您可以编写以下内容:

let settings = UIUserNotificationType.Alert.union(UIUserNotificationType.Badge)
Run Code Online (Sandbox Code Playgroud)

  • 方式太复杂了. (9认同)
  • 如果我没有错,你可以写`var options:NSTrackingAreaOptions = [.MouseEnteredAndExited,.MouseMo ved,.ActiveAlways]` (2认同)

Ah *_*oon 7

对我有用的是

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

  • 看起来几乎完全像上面接受的答案.考虑作为评论? (9认同)