繁体   English   中英

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

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

我想将结构的类型(“ 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的错误; 显然可以!

您的testFunc需要一个符合TestProtocol的类的实例。 因此,只需创建一个:

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

要传递您的myStruct类型:

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

testFunc(with: myStruct.self)

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