简体   繁体   中英

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")

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; yet it clearly does!

Your testFunc is expecting an instance of a class that conforms to TestProtocol . So just create one:

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

To pass a type of your myStruct :

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

testFunc(with: myStruct.self)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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