簡體   English   中英

如何解決 Protocol 'Result' as a type cannot conform to the protocol itself error in swift 5.6

[英]How to solve Protocol 'Result' as a type cannot conform to the protocol itself error in swift 5.6

如何在不知道協議的具體類型的情況下使用具有協議類型參數的方法?

例如,以下示例將產生“協議‘Result’作為類型不能符合協議本身”錯誤,因為 swift 不允許使用Result協議的 object 調用該方法

例子:

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();
}

function processResult不應該是通用的,通用將需要在編譯時符合Result的具體類型。

func processResult(_ result: Result)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM