[英]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例如,以下示例将产生“协议‘Result’作为类型不能符合协议本身”错误,因为 swift 不允许使用
Result
协议的 object 调用该方法
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. function
processResult
不应该是通用的,通用将需要在编译时符合Result
的具体类型。
func processResult(_ result: Result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.