簡體   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