Home > OS >  How to solve Protocol 'Result' as a type cannot conform to the protocol itself error in sw
How to solve Protocol 'Result' as a type cannot conform to the protocol itself error in sw

Time:03-20

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

CodePudding user response:

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)
  • Related