gpt4 book ai didi

swift - 将结构体的类型传递给协议(protocol)绑定(bind)的函数

转载 作者:行者123 更新时间:2023-11-30 10:38:49 25 4
gpt4 key购买 nike

我想将结构体的类型(“myStruct”)传递给由协议(protocol)(“TestProtocol”)绑定(bind)的函数(“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 的错误;但它显然确实如此!

最佳答案

使用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)

关于swift - 将结构体的类型传递给协议(protocol)绑定(bind)的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57300586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com