swift - Swift多协议一致性,编译错误
问题描述
我有下一个协议:
protocol ProtoAInput {
func funcA()
}
protocol ProtoA {
var input: ProtoAInput { get }
}
protocol ProtoBInput {
func funcB()
}
protocol ProtoB {
var input: ProtoBInput { get }
}
我想让 myStructC
符合两个协议ProtoA
和ProtoB
,只有一个input
属性。它本身只是对 的引用self
,StructC
也实现了ProtoAInput
和ProtoBInput
在单独的扩展中。
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
在这里拥有同时符合两种协议的变量。
解决方案
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
推荐阅读
- appium-android - 使用 TouchActions 在 android app + appium 中滚动
- file-upload - Yii2上传视频文件返回错误400
- node.js - Dialogflow 实现 webhook url 支持自签名证书吗?
- frama-c - 无法证明frama-c中的欧几里得除法
- amazon-web-services - AWS 子域指向子域
- javascript - 使画布在大于窗口大小的尺寸上可滚动
- c++ - 无法使用来自 bazel 的 boost/iostream 构建项目包
- php - 在多语言网站中生成链接
- compression - 压缩现有邮件文件,在 Roundcube (dovecot, centos) 中可读
- javascript - React Native 中的 React 导航图标