Generics Design Patterns

Generics Design Patterns

Marius Hartig

You can make common Design Patterns more powerful, if you combine them with Generics.

MVC

MVC Example

I saw in a lot of projects ViewController without logic, this ViewControllers was just holding a simple View with a information text in a label. I'm a big fan of keeping things simple, let us removing unnecessary ViewControllers too reduce the count of files in our project.


Setup Views & ViewControllers

Before i show you other tricks with Generics, i want quickly show you how i setup my Views and ViewControllers.


1. create setup Protocols

the protocols are separate for more flexibility


2. implement Setup Protocol in Views

view setup

3. implement Setup Protocol in ViewControllers

ViewController setup


In the HostingViewController we can setup our hostedView. Its make sense to setup first the view holder (ViewController) and than the View.


TableViewCell

In many projects i have the case that i want reuse the Cell as a View in a other View or ViewController. let us create something similar like the HostingViewController ^^


Now we can reuse Views in Cells, but normally a Cell is holding a Item. Ok than let us come more fancy :D

1. We need Protocols that is telling us that a Instance is holding a Item, let us call this ItemHolder.


2. We need a Protocol for updating the Cell.

here we can use the power of extensions and creating a default implementation for ItemHolders

3. We have to create a View that's implementing the ItemHolder  and ItemUpdatable Protocol.

4. Now we have also implement ItemHolder and ItemUpdatable Protocol too our TableViewCell.

update the cell

I hope this give you the motivation to play a little bit more with Generics ^^

Report Page