协议继承问题

Ale*_* S. 5 protocols ios associated-types swift protocol-inheritance

我尝试建立各种可以协同工作的协议。不幸的是,我无法让它们按照我想要的方式工作。看下面的代码,我认为我的目标很明显:我想要求一个符合协议X的类。如果它符合协议Y,但协议Y继承自协议X,则它也应被视为一个符合性的类。 。相反,我收到以下编译错误

Unable to infer associated type 'VC' for protocol 'ViewModelType'

Inferred type 'ExampleViewControllerType' (by matching requirement 'viewController') is invalid: does not conform to 'ViewType'

当前设置:

protocol ViewModelType: class {
    associatedtype VC: ViewType
    weak var viewController: VC! { get set }
}

class ExampleViewModel: ViewModelType {
    weak var viewController: ExampleViewControllerType!
}

protocol ViewType: class { }    
protocol ExampleViewControllerType: ViewType { }

class ExampleViewController: UIViewController, ExampleViewControllerType { 

}
Run Code Online (Sandbox Code Playgroud)

Sah*_*hil 1

不!!它不能是一致类(如果它符合协议 Y,但协议 Y 继承自协议 X,则它也应该被接受为一致类)。协议可以继承一个或多个其他协议,并且可以在其继承的要求之上添加更多要求。协议继承的语法与类继承的语法类似。您无法扩展一个协议以符合另一个协议。只有一个类满足协议强制执行的所有要求。您可以扩展协议以提供默认实现。

extension Y {
  // default implementations 
}
Run Code Online (Sandbox Code Playgroud)

了解更多协议继承