A common problem in developing iOS structures as UITableViewController and UICollectionViewControllers with list of different items. The most common solution is to create a protocol and all objects implement this protocol. Simple and functional.
I propose a solution using enums for my models do not have to implement a protocol that is related to an interface problem. Below the idea Enums with associated value.
//: Playground - noun: a place where people can play
import UIKit
import XCPlayground
enum CellData<A, B, C> {
case Number(A)
case Name(B)
case Money(C)
func title() -> String {
switch self {
case .Number(let number):
return "Number : \(number)"
case .Name(let name):
return "Name : \(name)"
case .Money(let money):
return "Money : \(money)"
}
}
}
final class MyTableViewController : UITableViewController {
let data : [CellData<Int,String,Double>] =
[CellData.Number(1),
CellData.Money(10.2),
CellData.Number(2),
CellData.Name("My name"),
CellData.Money(5.99),
CellData.Name("My name2")]
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count;
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = data[indexPath.row].title()
return cell
}
}
let tableViewController = MyTableViewController()
XCPlaygroundPage.currentPage.liveView = tableViewController.view
References and Thanks
This idea comes from two sources, the first is that blog: http://www.mokacoding.com/blog/swift-either/
Seriously accompany him. their content is always very good.
One thing I have to confess that after I began to see the videos of Chris Eidhof and Florian Kugler in https://talk.objc.io site and seriously am every day more interested in using Generics and Enums.