Swift协议继承。

9

我有一个 Swift 代码:

protocol ParentProtocol {
    // stuff
}

protocol ChildProtocol: ParentProtocol {
    // additional stuff
}

protocol FooProtocol {
    var variable: ParentProtocol? { get }
}

class Foo:FooProtocol {
    var variable: ChildProtocol?
}

我遇到了编译错误:
类型“Foo”不符合协议“FooProtocol”
我知道,根据FooProtocol,变量类型必须是ParentProtocol类型。另一方面,ChildProtocol继承自ParentProtocol,所以它也是一个ParentProtocol。
在这种情况下,有没有使用协议继承的解决方案?

@ShadowOf 是的,谢谢。带相关类型的解决方案按预期工作:https://dev59.com/V5jga4cB1Zd3GeqPIlQ4#38008288 - somedev
1
另外相关的(元类型的符合性和继承):协议本身不符合要求?,引用MartinR的评论,“即使使用protocol P:Q{}P也不能符合Q”。 - dfrib
1个回答

7

3
请注意,在符合此协议的类中,T 实际上可以成为任何类型,不仅限于 ParentProtocol 或其子类,例如 String - Shadow Of

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接