首页 > 解决方案 > 将结构的类型传递给协议绑定的函数

问题描述

我想将结构(“myStruct”)的类型传递给受协议(“TestProtocol”)绑定的函数(“testFunc”)

protocol TestProtocol {
    func getName() -> String
}

func testFunc <T: TestProtocol> (with type: T) {
    print ("testFunc")
}

struct myStruct: TestProtocol {
    var name: String
    func getName() -> String {
        return name
    }
}

testFunc(with: myStruct.self)

但是我得到 myStruct.Type 不符合 TestProtocol 的错误;但它显然是!

标签: swift

解决方案


用作T.Type参数类型。

protocol TestProtocol {
    func getName() -> String
}

func testFunc <T: TestProtocol> (with type: T.Type) {
    print ("testFunc")
}

struct MyStruct: TestProtocol {
    var name: String
    func getName() -> String {
        return name
    }
}

testFunc(with: MyStruct.self)

推荐阅读