简体   繁体   English

将结构的类型传递给协议约束的函数

[英]Pass the type of struct to a function bound by a protocol

I want to pass the type of my struct ("myStruct") to my function ("testFunc") which is bound by a protocol ("TestProtocol") 我想将结构的类型(“ 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)

But I get the error that myStruct.Type does not conform to TestProtocol; 但是我收到了myStruct.Type不符合TestProtocol的错误; yet it clearly does! 显然可以!

Your testFunc is expecting an instance of a class that conforms to TestProtocol . 您的testFunc需要一个符合TestProtocol的类的实例。 So just create one: 因此,只需创建一个:

testFunc(with: myStruct(name: "John"))

To pass a type of your myStruct : 要传递您的myStruct类型:

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

testFunc(with: myStruct.self)

Use T.Type as the parameter type. 使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM