Protocol Inheritance Problem

I am trying to configure various protocols that work hand in hand. Unfortunately, I cannot get them to work the way I want. Looking at the following code, I think my goal is obvious: I want a class that conforms to protocol X. If it conforms to protocol Y and protocol Y inherits from protocol X, it should also be accepted as the corresponding class. Instead, I get the following compilation error

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

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

Current setting:

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 { 

}
+4
source share
2 answers

I see what you get with “transitive” protocols, however your error is caused by your associatedtypeVC declaration , as shown in the error.

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

, , , , associatedtype.

An associatedtype .

VC associatedtype, , ViewModelType, , VC .

ExampleViewModel , typealias .

viewController ExampleViewControllerType, "inferred"

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

class ExampleViewModel: ViewModelType {
    typealias VC = ExampleViewControllerType
    weak var viewController: ExampleViewControllerType!
}

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

class ExampleViewController: UIViewController, ExampleViewControllerType {

}
+2

!! ( Y, Y X, ). , . . . , . .

extension Y {
  // default implementations 
}

+1

Source: https://habr.com/ru/post/1657731/


All Articles