简体   繁体   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

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.

相关问题 Swift 如何在协议中符合不同的关联类型 - Swift how to conform to different associate type in a protocol Swift:通用类型符合协议 - Swift: Generic Type conform Protocol 类型不符合协议Swift - Type does not conform to protocol Swift Swift - 类型“*”不符合协议“*” - Swift - Type '*' does not conform to protocol '*' 类型任何协议不能符合协议 - Type any Protocol cannot conform to Protocol 类型“ SomeVC”不符合协议“ NextLevelDelegate”(与Swift 4.1.2编译) - Type 'SomeVC' cannot conform to protocol 'NextLevelDelegate' (compiled with Swift 4.1.2) 协议类型“Any”的值不能符合“Equatable”Swift - Value of protocol type 'Any' cannot conform to 'Equatable' Swift SwiftUI 收到“源文件中的编辑器占位符”和“作为类型的协议‘Equatable’不能符合协议本身”错误 - SwiftUI receiving "Editor placeholder in source file" and "Protocol 'Equatable' as a type cannot conform to the protocol itself" errors swift 将字典转换为 jsonString 错误:协议类型 'Any' 不能符合 'Encodable' 因为只有具体类型才能符合协议 - swift Convert dictionary to jsonString error : Protocol type 'Any' cannot conform to 'Encodable' because only concrete types can conform to protocols Swift错误类型&#39;usersVC&#39;不符合协议&#39;UITableViewDataSource&#39; - Swift Error type 'usersVC' does not conform to protocol 'UITableViewDataSource'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM