将显式展开的枚举类型的 属性 与常量进行比较

Comparing property of explicitly unwrapped enum type to constant

我有一个像这样的枚举:

enum MyEnumType{
case Case1
case Case2
}

和一个 属性 定义如下:

var myProperty:MyEnumType!

...声明为可选类型,因为我的代码逻辑要求它只能在实例初始化后设置。

在我的一种方法中,我试图将 属性 与类型的预设值(大小写)之一进行比较,如下所示:

if myProperty == .Case1 {
    // some code
}

然而,编译器抱怨:

Could not find member "Case1"

...直到我将 ! 添加到变量中,如下所示:

if myProperty! == .Case1 {
    // some code
}

有意义的是 MyEnumType! 类型中没有记忆 .Case1(可选):.Case1 它是 MyEnumType 类型的值(非可选 - 技术上 它们是两种不同的类型)。

但是,如果我仍然必须附加 ! 我什么时候访问它?

编辑: 我只需要在比较中附加 ! (==)。例如,下面的(赋值)代码编译没有问题:

myProperty = .Case1

编辑 2: 好的,这里是实际的类型名称/变量名称(它不是机密的或任何东西)只是为了确保我没有更改任何内容问题的改编:

类型:

enum OrderingDirection : Printable {    
    case Ascending
    case Descending

    var description: String {
        switch self {
        case .Ascending:
            return "Ascending"    
        case .Descending:
            return "Descending"
        }
    }
}

这是我的 class 的 属性 声明:

var orderDirection:OrderingDirection!

...这里是 if 块,我在其中尝试将显式解包的可选类型与其中一种情况进行比较:

if orderDirection! == .Ascending { // Compiler error if I omit the "!"
    orderDirection = .Descending
}
else{
    orderDirection = .Ascending
}

(我只是切换值)

编辑 3: 正如@user2194039 所建议的,我尝试 not 在比较中省略枚举类型:我替换了

if orderDirection == .Ascending {

与:

if orderDirection == OrderingDirection.Ascending {

...现在错误消失了(不再需要解包 !)。作为旁注,无论如何添加 ! 都不会产生任何警告。

编辑 4: 为了保险起见,我创建了一个新项目,iOS 单视图应用程序(通用,Swift)。我将包含的视图控制器 subclass 修改为以下内容:

import UIKit

enum OrderingDirection : Printable {

    case Ascending
    case Descending

    var description: String
        {
            switch self {
            case .Ascending:
                return "Ascending"

            case .Descending:
                return "Descending"
            }
    }
}


class ViewController: UIViewController {

    var orderDirection:OrderingDirection!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        if orderDirection == .Ascending { // <- No "!", yet no error

        }
        else{

        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

...而且,和我实际项目不同的是,没有报编译错误。在我的代码中一定有一些与其他实体的相互作用,但现在我不太清楚它可能是什么。

编辑 5:(进一步考虑)后续 编译:

if orderDirection as OrderingDirection == .Ascending {

以下,

if self.orderDirection == .Ascending {

如果替换

是否仍然会出现编译错误
if orderDirection! == .Ascending {...}

if orderDirection == OrderingDirection.Ascending {...}

试试看?请注意,我从比较中删除了 ! 并指定了 OrderingDirection 枚举以及特定情况。

如果这样确实消除了错误,那么编译器的混淆一定是有原因的。您是否有多个 Enum 和一个名为 Ascending 的案例? Enum 是框架或库的一部分吗?