Why can't I use 'Type' as the name of an enum embedded in a struct?

前端 未结 2 1205
死守一世寂寞
死守一世寂寞 2021-01-27 01:23

The following fails to compile:

struct S1 {
    enum Type {
        case One, Two, Three
    }

    let e1 : Type
    let i : Int
}

func f1(e : S1.Type) {
    S         


        
2条回答
  •  被撕碎了的回忆
    2021-01-27 01:49

    You can do it like this (as mentioned before, Type is also used within the core of Swift. That's why the compiler is kind of confused). Type used as a name works if the enum is not nested:

    enum Type {
            case One, Two, Three
    }
    
    struct S1 {
    
        let e1 : Type
        let i : Int
    }
    
    func f1(e : Type) {
       var x = S1(e1: Type.One, i: 1)
    }
    
    f1(Type.One)
    

    if you use another name for the enum, you can still nest it:

     struct S2 {
    
    
        enum Kind {
            case One, Two, Three
        }
    
        let e1 : Kind
        let i : Int
    }
    
    func f2(e : S2.Kind) {
       var x = S2(e1: S2.Kind.One, i: 1)
    }
    
    f2(S2.Kind.One)
    

提交回复
热议问题