Search code examples
swiftinputmvvmuikitviewmodel

Custom Protocol conformances for ViewModel in swift in MVVM for Input and Output types


I want to create base protocol for Input, Output, and ViewModel for my MVVM architecture. Here is my current implementation for that purpose.

I really want to write code-like-that.

But the problem is that XCode complains that No type for 'Self.Input' can satisfy both 'Self.Input == any MyViewModelInput' and 'Self.Input : ViewModelInput' when I try to declare MyViewModel protocol.

Here are my topics that I want to be satisfied:

  • ViewModelInput is generic protocol that allows me to use default implementation for some functions
  • ViewModelOutput is generic protocol that allows me to use default implementation for some functions
  • ViewModel's Input and Output are typed by ViewModelInput and ViewModelOutput
  • There is MyViewModel protocol that conforms to the ViewModel protocol with appropriate Input and Output associatedtype-s

protocol ViewModelInput {
    func onViewDidLoad()
}

extension ViewModelInput {
    func onViewDidLoad() {}
}

protocol ViewModelOutput { }

protocol ViewModel: AnyObject {
    associatedtype Input: ViewModelInput
    associatedtype Output: ViewModelOutput
}

protocol MyViewModelInput: ViewModelInput { }
protocol MyViewModelOutput: ViewModelOutput { }

// [On this bottom line there is error: `No type for 'Self.Input' can satisfy both 'Self.Input == any MyViewModelInput'
protocol MyViewModel: ViewModel           
    where Input == MyViewModelInput, 
          Output == MyViewModelOutput { }

final class DefaultMyViewModel: MyViewModel { }

How can I change the code so that is satisfies my criteria and there is no remaining error?


Solution

  • According to @Joakim Danielson,

    Changing == to : in the where condition will silence the compiler error

    And it worked adequately.