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
1 2 3 4 | enum Either <A, B> { case Left (A) case Right (B) } |
Either allows us to write clear statements, which are themselves explanations for themselves:
1 2 3 4 5 6 7 8 | let x: <ither <SomeType, AnotherType> = ... switch x { case .Left (let someTypeValue): // do something with someTypeValue case .Right (let anotherTypeValue): // do something with anotherTypeValue } |
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>.
1 2 3 4 5 | let data: Either <CellModel, BannerModel> = ... func tableView (_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | func tableView (_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let item = data [indexPath.row] let identifier: String = { item switch { case .Left: return pizzaCellIdentifier case .Right: return adCellIdentifier } } () let cell = tableView.dequeueReusableCell (withIdentifier: identifier, for: indexPath) item switch { case .Left (let pizza): configure (cell, with: pizza) case .Right (let ad): configure (cell, with: ad) } return cell } |
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