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

前端 未结 2 1232
死守一世寂寞
死守一世寂寞 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条回答
  •  萌比男神i
    2021-01-27 01:41

    Steve was right, it's a keyword. Here's the relevant part of the spec:

    Keywords reserved in particular contexts: associativity, convenience, dynamic, didSet, final, get, infix, inout, lazy, left, mutating, none, nonmutating, optional, override, postfix, precedence, prefix, Protocol, required, right, set, Type, unowned, weak, and willSet. Outside the context in which they appear in the grammar, they can be used as identifiers.

    Apparently, a top level enum Type is fine, but one embedded in a struct is not. The language reference section on Types > Metatype Types explains why:

    Metatype Type

    A metatype type refers to the type of any type, including class types, structure types, enumeration types, and protocol types.

    The metatype of a class, structure, or enumeration type is the name of that type followed by .Type. The metatype of a protocol type—not the concrete type that conforms to the protocol at runtime—is the name of that protocol followed by .Protocol. For example, the metatype of the class type SomeClass is SomeClass.Type and the metatype of the protocol SomeProtocol is SomeProtocol.Protocol.

提交回复
热议问题