swift - 将结构的类型传递给协议绑定的函数
问题描述
我想将结构(“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 的错误;但它显然是!
解决方案
用作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)
推荐阅读
- mod-rewrite - 如何重写nextcloud的url
- swift - ViewController 未按预期执行 segue
- node.js - 如何正确转义 node-postgres 查询中的单引号?
- javascript - 我们可以在组件树的不同级别上有多个上下文吗?
- python - 如何在两个熊猫数据框之间找到更新的行
- html - '如何添加'鼠标悬停和鼠标悬停?
- visual-studio - 为什么在迁移到 Visual Studio 2019 后筛选器不再起作用?
- angular - 是否可以使用 ng.probe 获取/设置环境变量?
- bash - Bash 脚本,命令结束后更新输出
- javascript - If a PHP server script calls a javascript file with a secret key is it exposed?