首页 > 解决方案 > Swift多协议一致性,编译错误

问题描述

我有下一个协议:

protocol ProtoAInput {
    func funcA()
}

protocol ProtoA {
    var input: ProtoAInput { get }
}

protocol ProtoBInput {
    func funcB()
}

protocol ProtoB {
    var input: ProtoBInput { get }
}

我想让 myStructC符合两个协议ProtoAProtoB,只有一个input属性。它本身只是对 的引用selfStructC也实现了ProtoAInputProtoBInput在单独的扩展中。

struct StructC: ProtoA, ProtoB {
    var input: ProtoAInput & ProtoBInput { return self }
}

extension StructC: ProtoAInput {
    func funcA() { print("funcA") }
}

extension StructC: ProtoBInput {
    func funcB() { print("funcB") }
}

let s = StructC()
s.funcA()
s.funcB()

Swift 5.3 编译器无法构建此代码并出现以下错误:

Type 'StructC' does not conform to protocol 'ProtoA'

Type 'StructC' does not conform to protocol 'ProtoB'

此代码是否违反了任何编译规则?我不明白为什么我不能input在这里拥有同时符合两种协议的变量。

标签: swift

解决方案


struct StructC: ProtoA, ProtoB {
    var input: ProtoAInput & ProtoBInput { return self }
}

而不是上面你需要类似下面的东西

extension ProtoA where Self == StructC {
    var input: ProtoAInput { self }
}

extension ProtoB where Self == StructC {
    var input: ProtoBInput { self }
}

struct StructC: ProtoA, ProtoB {
}

测试和使用 Xcode 12.1 / iOS 14.1

演示


推荐阅读