Learn Swift Either enum

Enum in Swift is very powerful and versatile. Swift enum is a type with its own rules, with support for both methods and initializers, and Associated Value features that allow us to use it conveniently.

Example of enum power is Optional type. Optional is defined as 1 enum with 2 cases. Case None demonstrates the absence of value (nil), while the Some wrapped case has an appearance of its associated value.

A strong but less known type, which we can implement as 1 enum is Either.

Either

Type Either represents two faces, 1 value can be 1 type or other

Either allows us to write clear statements, which are themselves explanations for themselves:

Thus, Either may not be very practical, but the following is the example of good Either usage: adding extra cells in 1 Table View or Collection View.

Add cells in Table View using Either

Sometimes, we need to display data in the Table or Collection Views with dedicated cells to call an action or banner ads – allowing users to remove these in in-app purchase.

We can do this by displaying a banner instead of a real item for a given index path and moving the index used to get the next item we want to display from the data array, based on the number The number of cells banner displayed.

Or we can use Either.

In addition to cell models, the dev can give the data source an array of Either <CellModel, BannerModel>.

Thus, in the tableView method (_: cellForRowAt 🙂 we can get the item for the current index segment, move and act according to its type as follows:

This approach seems to be more consistent with me. It does not depend on any algorithm, supports code reception more easily, and I realize that switch-case construction is a very good way to explain logic to your source code.

The dev can see full code in Github

ITZone via IDE Academy via Mokacoding

Share the news now