如何解决 Protocol 'Result' as a type cannot conform to the protocol itself 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
协议
示例:
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();
}
函数 processResult
不应该是泛型的,泛型需要在编译时符合 Result
的具体类型。
func processResult(_ result: Result)
如何在不知道协议的具体类型的情况下使用具有协议类型参数的方法?
例如,下面的示例会产生“协议 'Result' 作为类型不能符合协议本身”的错误,因为 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();
}
函数 processResult
不应该是泛型的,泛型需要在编译时符合 Result
的具体类型。
func processResult(_ result: Result)