【问题标题】:Swift "Ambiguous use of operator '=='"斯威夫特“运算符'=='的模棱两可的使用”
【发布时间】:2014-06-21 12:16:57
【问题描述】:

我正在尝试将UIUserNotificationType 的实例(即RawOptionSet)与某个值进行比较:

var types: UIUserNotificationType = ...
if types == UIUserNotificationType.None { // <-- Error here
     ...
}

但是在第二行出现错误:

运算符'=='的模糊使用

关于这可能来自哪里的任何想法?

(我可以types.toRaw() == 0,但我觉得它很丑……)


UIUserNotificationType 声明供参考:

struct UIUserNotificationType : RawOptionSet {
    init(_ value: UInt)
    var value: UInt
    static var None: UIUserNotificationType { get }
    static var Badge: UIUserNotificationType { get }
    static var Sound: UIUserNotificationType { get }
    static var Alert: UIUserNotificationType { get }
}

【问题讨论】:

  • types.value == UIUserNotificationType.None.value 怎么样?因为 UIUserNotificationType 是 Equatable,所以它对我来说仍然是一个错误
  • 我还不熟悉这个。所以我先把它放在这里作为一个建议。我认为您应该使用可选绑定if let someType = types.None) { // do something with someType }
  • @markhunte 感谢您的建议,但它不起作用。 types 显然不是可选的。

标签: compiler-errors operator-overloading swift


【解决方案1】:

试试这个,而我试着看看你的有什么问题(这行得通):

    var types = UIUserNotificationType.Sound | UIUserNotificationType.Badge

    switch types {
        case UIUserNotificationType.None:
            println("None")
        case UIUserNotificationType.Badge | UIUserNotificationType.Sound :
            println("Badge & Sound") // This will print
        case UIUserNotificationType.Badge:
            println("Badge")
        case UIUserNotificationType.Alert:
            println("Alert")
        case UIUserNotificationType.Sound:
            println("Sound")
        default:
            println("default")
    }

这也有效,但它看起来确实是原版没有的错误:

if types.value == UIUserNotificationType.None.value {
        println("None, too")
}

【讨论】:

  • 如果RawOptionSet 有多个值,它的行为如何?即let types = UIUserNotificationType.Badge | .Sound.
猜你喜欢
  • 1970-01-01
  • 2017-07-22
  • 2017-03-24
  • 2015-05-15
  • 1970-01-01
  • 1970-01-01
  • 2016-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多