1

I'm trying to add some base-classes to an iOS app using MVVM, to make it easier and enforce a common class relationship.

Sadly, I'm running into the following issue:

error: MyPlayground.playground:27:7: error: type 'ListView' does not 
conform to protocol 'MVVMView'
class ListView: MVVMView {

I'm not sure why this happens and kind of breaks my idea of "forcing" my code into this architecture. Is there something obvious I'm missing? Is there a workaround for me to fix this and keep the "enforced" architecture?

Note: I'm running on swift 5.

/**
 Base classes for MVVM
 */
protocol MVVMViewModel {

}

protocol MVVMView {
    associatedtype ViewModel: MVVMViewModel
    var viewModel: ViewModel { get }
}

/**
 Simple viewmodel, only used by protocol so it can be replaced when testing
 */
protocol ListViewModelProtocol: MVVMViewModel {

}

class ListViewModel: ListViewModelProtocol {

}

/*
 Simple view
 */
class ListView: MVVMView {
    typealias ViewModel = ListViewModelProtocol
    var viewModel: ListViewModelProtocol

    init(viewModel: ListViewModelProtocol) {
        self.viewModel = viewModel
    }
}
KevinSkyba
  • 317
  • 3
  • 7
  • I feel like this is somewhat related to [this problem](https://stackoverflow.com/questions/33112559/protocol-doesnt-conform-to-itself). Specifically, `ListViewModelProtocol` is not a concrete conformance of `MVVMViewModel`. Changing it to `ListViewModel` should work. – Sweeper Jul 07 '19 at 07:42

1 Answers1

2

This is a tricky case. The solution is to replace

associatedtype ViewModel: MVVMViewModel 

with

associatedtype ViewModel = MVVMViewModel

Why?

  1. You described MVVMView as something that has a viewModel propery with type that conforms to MVVMViewModel. You can try to create a class like this

    class AnyView: MVVMView { typealias ViewModel = MVVMViewModel var viewModel: MVVMViewModel

    init(viewModel: MVVMViewModel) {
        self.viewModel = viewModel
    }
    

    }

You'll have the error, saying MVVMViewModel does not conform to MVVMViewModel So MVVMViewModel does not conform to itself as any protocol in swift

  1. Actually I didn't know this, but protocol also does not conform to its parent That's why ListViewModelProtocol doesn't conform to MVVMViewModel

You can find more detailed explanation, here I have found one Protocol doesn't conform to itself?

Tiran Ut
  • 942
  • 6
  • 9