ios Swift 2.0 - 二元运算符“|” 不能应用于两个 UIUserNotificationType 操作数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30761996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift 2.0 - Binary Operator "|" cannot be applied to two UIUserNotificationType operands
提问by Nikita Zernov
I am trying to register my application for local notifications this way:
我正在尝试以这种方式为本地通知注册我的应用程序:
UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil))
In Xcode 7 and Swift 2.0 - I get error Binary Operator "|" cannot be applied to two UIUserNotificationType operands
. Please help me.
在 Xcode 7 和 Swift 2.0 中 - 我收到错误Binary Operator "|" cannot be applied to two UIUserNotificationType operands
。请帮我。
回答by Mick MacCallum
In Swift 2, many types that you would typically do this for have been updated to conform to the OptionSetType protocol. This allows for array like syntax for usage, and In your case, you can use the following.
在 Swift 2 中,您通常会执行此操作的许多类型已更新以符合 OptionSetType 协议。这允许使用类似数组的语法,并且在您的情况下,您可以使用以下内容。
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
And on a related note, if you want to check if an option set contains a specific option, you no longer need to use bitwise AND and a nil check. You can simply ask the option set if it contains a specific value in the same way that you would check if an array contained a value.
并且在相关说明中,如果要检查选项集是否包含特定选项,则不再需要使用按位 AND 和 nil 检查。您可以简单地询问选项集是否包含特定值,就像检查数组是否包含值一样。
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge], categories: nil)
if settings.types.contains(.Alert) {
// stuff
}
In Swift 3, the samples must be written as follows:
在Swift 3 中,示例必须按如下方式编写:
let settings = UIUserNotificationSettings(types: [.alert, .badge], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
and
和
let settings = UIUserNotificationSettings(types: [.alert, .badge], categories: nil)
if settings.types.contains(.alert) {
// stuff
}
回答by Bobj-C
You can write the following:
您可以编写以下内容:
let settings = UIUserNotificationType.Alert.union(UIUserNotificationType.Badge)
回答by Ah Ryun Moon
What worked for me was
对我有用的是
//This worked
var settings = UIUserNotificationSettings(forTypes: UIUserNotificationType([.Alert, .Badge, .Sound]), categories: nil)
回答by CodeSteger
This has been updated in Swift 3.
这已在 Swift 3 中更新。
let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)