Swift enum loses initialized values when set as a property?

前端 未结 1 1837
星月不相逢
星月不相逢 2020-12-12 04:12

I\'ve found a work-around, but this problem is vexing me and I thought I\'d share in case anyone else is having the same problem. Would love to know why this is happening.

相关标签:
1条回答
  • 2020-12-12 04:56

    Property foo is not MyEnum, but ImplicitlyUnwrappedOptional<MyEnum> aka MyEnum!. Unlike many other cases, switch does not implicitly unwrap it.

    You have to unwrap it manually:

        if let foo = foo {
            switch foo {
            case .ABC: println("ABC foo")
            case .DEF: println("DEF foo")
            case .GHI: println("GHI foo")
            default: println("no foo")
            }
        }
        else {
            println("nil foo")
        }
    

    OR force unwrap with ! if you are sure foo is not nil, :

        switch foo! {
        case .ABC: println("ABC foo")
        case .DEF: println("DEF foo")
        case .GHI: println("GHI foo")
        default: println("no foo")
        }
    

    OR match with ImplicitlyUnwrappedOptional<Enum> as is:

        switch foo {
        case .Some(.ABC): println("ABC foo")
        case .Some(.DEF): println("DEF foo")
        case .Some(.GHI): println("GHI foo")
        default: println("no foo")
        }
    
    0 讨论(0)
提交回复
热议问题