Skip to content

Instantly share code, notes, and snippets.

@bartcone
Last active November 2, 2015 18:08
Show Gist options
  • Save bartcone/b58c7d7003b9e17f707f to your computer and use it in GitHub Desktop.
Save bartcone/b58c7d7003b9e17f707f to your computer and use it in GitHub Desktop.
metatypes? bad idea?
struct Section {
let info: String
}
struct Row {
let text: String
}
class BaseClass: NSObject {}
class SubclassUno: BaseClass {}
class SubclassDos: BaseClass {}
extension BaseClass: Configurable {}
protocol Configurable {
func configure(row: Row)
}
extension Configurable where Self: BaseClass {
func configure(row: Row) {
print("Custom config for BaseClass")
}
}
extension Configurable where Self: SubclassUno {
func configure(row: Row) {
print("Custom config for SubclassUno")
}
}
extension Configurable where Self: SubclassDos {
func configure(row: Row) {
print("Custom config for SubclassDos")
}
}
class Simulator {
let rows = [
Row(text: "BaseClass-Sample-Data"),
Row(text: "SubclassUno-Sample-Data"),
Row(text: "SubclassDos-Sample-Data")
]
let cells = [
BaseClass(),
SubclassUno(),
SubclassDos()
]
func simulate() {
for i in 0..<cells.count {
go(cells[i], indexPath: i)
}
}
// `cell` will ultimately be UITableViewCell in `cellForRowAtIndexPath`
func go(cell: BaseClass, indexPath: Int) {
let row = rows[indexPath]
if cell.dynamicType === BaseClass.self {
cell.configure(row)
} else if cell.dynamicType === SubclassUno.self {
let c = cell as! SubclassUno
c.configure(row)
} else if cell.dynamicType === SubclassDos.self {
let c = cell as! SubclassDos
c.configure(row)
}
}
}
let s = Simulator()
s.simulate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment