SomeProtocol.Protocol和SomeProtocol.Type之间的根本区别是什么?

时间:2020-05-07 10:03:28

标签: swift swift-protocols metatype

偶然地,我观察到SomeProtocol.ProtocolSomeProtocol.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.Protocolbecause 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 表示“)

0 个答案:

没有答案