我正在尝试创建一个类(ProtocolPrinter
),它将协议作为泛型参数。为什么这段代码无法编译?
import Foundation
@objc protocol MyProtocol {
func foo()
}
class MyConformingClass: MyProtocol {
func foo() {
print("Foo!")
}
}
class ProtocolPrinter<T: Protocol> {
func printT() {
print("T: \(T.self)")
}
func dosomethingWithObject(_ object: T) {
if let object = object as? MyProtocol {
object.foo()
} else {
print("I don't know what object this is: \(object).")
}
}
}
let x = MyConformingClass()
x.foo() // Foo!
let myProtocolMeta: Protocol = MyProtocol.self // No error.
ProtocolPrinter<MyProtocol>() // 'ProtocolPrinter' requires that 'MyProtocol' inherit from 'Protocol'
ProtocolPrinter<MyProtocol.self>() // (treats "<" and ">" as operators)
ProtocolPrinter<MyProtocol.Type>() // 'ProtocolPrinter' requires that 'MyProtocol.Type' inherit from 'Protocol'
ProtocolPrinter<MyProtocol.Type.self>() // (treats "<" and ">" as operators)
ProtocolPrinter<MyProtocol.Protocol>() // type 'MyProtocol.Protocol' does not confor
ProtocolPrinter<MyProtocol.Protocol.self>() // (treats "<" and ">" as operators)
ProtocolPrinter<MyProtocol.Protocol.Type>() // type 'MyProtocol.Protocol.Type' does not conform to protocol 'MyProtocol'
ProtocolPrinter<MyProtocol.Protocol.Type.self>() // (treats "<" and ">" as operators)
ProtocolPrinter<MyProtocol.Protocol.Protocol>() // cannot use 'Protocol' with non-protocol type 'MyProtocol.Protocol'
ProtocolPrinter<MyProtocol.Protocol.Protocol.Type>() // cannot use 'Protocol' with non-protocol type 'MyProtocol.Protocol'
Protocol
类型是什么?!ProtocolPrinter
可以与符合Protocol
的某些内容一起工作。通过拥有class ProtocolPrinter<T: Protocol>
,您已经将其作为要求。然而,MyProtocol
从未符合Protocol
。MyProtocol.self
符合Protocol
,它是一个类。这对于所有的@objc
协议都是正确的。我还更新了我的答案,加入了更多的测试用例。 - Coder-256