偶然地,我观察到SomeProtocol.Protocol
和SomeProtocol.Type
类型之间在行为上存在一些差异(在此之前,我认为它们是同一回事!):
public protocol P {
}
public class C: P {
}
protocol Q: P {}
P.self is P.Protocol // true
P.self is P.Type // false
Q.self is P.Protocol // false
Q.self is P.Type // false
C.self is P.Protocol // false
C.self is P.Type // true
// this seems to be consistent with function invocation expressions, which is expected
func a(_ x: P.Protocol) { }
func b(_ x: P.Type) { }
a(P.self)
b(P.self) // error
a(Q.self) // error
b(Q.self) // error
a(C.self) // error
b(C.self)
令我惊讶的是P.self is P.Protocol
,because I know protocols don't conform to themselves,所以我希望它是真的...
无论如何,我看不出.Protocol
和.Type
之间的根本差异导致了这种行为差异。我希望这两种语法平均值可能有些微不同...
我检查了Swift guide on meta types,它只是说:
类,结构或枚举类型的元类型是 该类型后跟
.Type
。协议类型的元类型-不是 在运行时符合协议的具体类型是 该协议的名称,后跟.Protocol
。例如, 类类型SomeClass
的元类型是SomeClass.Type
并且 协议SomeProtocol
的元类型是SomeProtocol.Protocol
。
似乎没有意识到SomeProtocol.Type
的存在!
.Protocol
和.Type
有什么区别?
(如果不清楚,我正在寻找一种答案,类似“ .Protocol
表示此,其中.Type
表示“)