简体   繁体   中英

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

How can I work with methods that have parameters of a protocol type without knowing the specific type of the protocol?

For instance the following example would produce a "Protocol 'Result' as a type cannot conform to the protocol itself" error, because swift does not allow to call the method with an object of the Result protocol

Example:

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

The function processResult shouldn't be generic, a generic will require a concrete type that conforms to Result at compile time.

func processResult(_ result: Result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM