【问题标题】:Swift 2.0 - Binary Operator "|" cannot be applied to two UIUserNotificationType operandsSwift 2.0 - 二元运算符“|”不能应用于两个 UIUserNotificationType 操作数
【发布时间】:2026-02-20 05:20:13
【问题描述】:

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

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。请帮帮我。

【问题讨论】:

  • 带“()”的环绕声对我有用 UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: (UIUserNotificationType.Alert | UIUserNotificationType.Badge), categories: nil))
  • 现在我有:Could not find an overload '|' that accepts the supplied arguments
  • 我没有别的想法,抱歉。

标签: ios swift swift2


【解决方案1】:

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

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

在相关说明中,如果您想检查选项集是否包含特定选项,则不再需要使用按位 AND 和 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
}

【讨论】:

  • 如果你有flags |= .Alert?可以用flags = [flags, .Alert]吗?
  • 即,这是否被视为一个值唯一的集合或可能导致最终值不正确的数组?
  • @user3246173 这取决于 flags 变量的声明方式。如果标志的类型显式声明为UIUserNotificationType,即var flags: UIUserNotificationType = [.Alert, .Badge],那么它将被视为一个集合,您可以使用集合实例方法添加一个元素,如insert()union()unionInPlace()、或使用您提到的方法,而不必担心重复。
  • 如果你没有明确声明标志的类型为UIUserNotificationType并在你的声明中使用var flags = [UIUserNotificationType.Alert, UIUserNotificationType.Badge]之类的东西,那么标志的类型将被推断为[UIUserNotificationType],并将元素添加到通过append() 或其他方法将导致重复。对于后者,您可以简单地使用数组作为输入初始化UIUserNotificationType 的实例,一切都会好起来的,但为了清楚起见,我建议使用基于集合的方法。
【解决方案2】:

你可以这样写:

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

【讨论】:

  • 哇,这看起来很可怕! NSTrackingAreaOptions.MouseEnteredAndExited.union(NSTrackingAreaOptions.MouseMoved).union(NSTrackingAreaOptions.ActiveAlways),但感谢您提供有效的解决方案
  • 如果我没记错你可以写var options : NSTrackingAreaOptions =[.MouseEnteredAndExited,.MouseMo‌​ved,.ActiveAlways]
【解决方案3】:

对我有用的是

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

【讨论】:

  • 看起来几乎完全像上面接受的答案。考虑作为评论?
【解决方案4】:

这已在 Swift 3 中更新。

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

【讨论】: