我有一個符合特定協議的類。
protocol MyProtocol {
func doSomething()
}
class MyClass: MyProtocol {
func doSomething() { }
}
在另一個類中,我有一個函式,其輸入引數為MyProtocol。
func customFunction(with: MyProtocol) { }
當我使用輸入引數MyClass(實際上符合MyProtocol)呼叫此函式時,我收到一條錯誤訊息,指出MyClass 不符合 MyProtocol
customFunction(with: MyClass)
我知道我實際上應該使用MyClass的實體,但我只需要MyClass的型別。有解決方法嗎?
uj5u.com熱心網友回復:
您需要定義函式以將型別而不是型別的實體作為引數
func customFunction(with type: MyProtocol.Type) {}
然后你可以用一個符合協議的型別來呼叫它
customFunction(with: MyClass.self)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/534962.html
標籤:ios迅速仿制药
上一篇:如何在SwiftUI的macOS的視圖選單中禁用甚至洗掉EnterFullScreen選項?
下一篇:如何洗掉macOS中的所有命令?
