在不知道協議的具體型別的情況下,如何使用具有協議型別引數的方法?
例如下面的例子會產生一個“Protocol 'Result' as a type cannot conform to the protocol itself”錯誤,因為 swift 不允許使用Result協議物件呼叫方法
例子:
protocol Result {
var foo: String { get }
}
struct ResultImpl: Result {
var foo = "foo"
}
struct ResultImpl2: Result {
var foo = "foo2"
}
protocol Calculator {
func processResult<T: Result>(_ result: T)
}
struct CalculatorImpl: Calculator {
func processResult<T: Result>(_ result: T) {
let _ = result.foo
}
}
func test(){
let result: Result = getResult() // get anything that implements Result interface
let calc = CalculatorImpl();
let _ = calc.processResult(result) // Protocol 'Result' as a type cannot conform to the protocol itself
}
func getResult() -> Result {
return Int.random(in: 0...1) == 0 ? ResultImpl(): ResultImpl2();
}
uj5u.com熱心網友回復:
該函式processResult不應該是泛型的,泛型將需要Result在編譯時符合的具體型別。
func processResult(_ result: Result)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/447167.html
