1

I got an interesting question about the VIPER architecture and Generics protocol.

It seems that the Presenter and Interactor communicates a lot, (for fetching and receiving data), but the "Output" functions of the Interactor will always be the same

Something like:

func dataFetched(object: JSONObject)

And if you have 10 modules you'll have 10 times this function with only the JSONObject that change...

Is that possible to use something like

protocol Ouput {
  associatedType Object
  func dataFetched(object: Object)
}

And choose the type of Object in the presenter?

2
  • 1
    Nope, that's not possible. It's actually one of the problems of VIPER - the abstraction results in rather big amount of protocol code which is also often duplicated. You can create parent protocols though. E.g. dataFetched will generally also have a pair function dataFailed(error:) and that can be abstracted to a parent protocol.
    – Sulthan
    Mar 8, 2018 at 14:39
  • Hmm, Kinda disapointing, I wanted to avoid a plenty of protocols. Yeah my protocol actually have 3 functions didFetch(object: Object) didFetch(objects: [Objects]) didFail(error: Error?) But I don't want to have an output protocol for every models, cause it'll lead to have N times the didFetch/didFail functions.. But if not possible, I'll do another way. Mar 8, 2018 at 14:48

1 Answer 1

2

If JSONObject is an Entity presenter should not know about it. Instead, interactor should return pleomorphic type that can be converted to a ViewModel. And then presenter can pass this ViewModel to the view. So interactor output could look like:

func didFetched(object: ViewModelConvertible)
9
  • Yes JSONObject will be models used across the app. So I should create a class above all my entities and use that type instead of associatedType/typealias ? Mar 8, 2018 at 14:34
  • But there's no viewModel into VIPER architecture. Presenter directly communicate with the ViewController itself with method like view?.update(with: JSONObject) or view?.displayAlert(for: error). Mar 8, 2018 at 14:36
  • In VIPER models or entities, can`t be used across the app. Because changes in the entities should not affect presenter. ViewModel in VIPER is a simple struct without any logic. Presenter passes to view this ViewModels and view just sets its controls with values from this ViewModel Mar 8, 2018 at 14:40
  • But by adding a ViewModel you add another layer nah? So the conversion of ViewModelConvertible to the entity will be done in that viewModel ? Mar 8, 2018 at 14:43
  • 1
    The whole purpose of VIPER is the creation of independent layers, and the best way achieve it in Swift, I think, is a polymorphism with protocols Mar 8, 2018 at 14:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.