Swift协议作为类的通用参数

编码器256

我正在尝试创建一个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'
编码器256

事实证明,您需要指定@objc protocol所有其他协议(必须也必须是@objc protocols)都符合的单个协议,例如:

import Foundation

@objc protocol SuperProtocol {}
@objc protocol MyProtocol: SuperProtocol {
    func foo()
}

class MyConformingClass: MyProtocol {
    func foo() {
        print("Foo!")
    }
}

class ProtocolPrinter<T: SuperProtocol> {
    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!
MyProtocol.Protocol.self
let myProtocolMeta: Protocol = MyProtocol.self

ProtocolPrinter<MyProtocol>().dosomethingWithObject(MyConformingClass()) // Foo!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章