Created
April 16, 2018 13:22
-
-
Save TerryCK/b647d26aed45ec6412c83f4d586bae4b to your computer and use it in GitHub Desktop.
GenericDataSource for UITableView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ViewController.swift | |
// GenericViewController | |
// | |
// Created by 陳 冠禎 on 16/04/2018. | |
// Copyright © 2018 AppCoda. All rights reserved. | |
// | |
import UIKit | |
final class ViewController<T: DataSourceProtocol>: UIViewController, UITableViewDelegate, UITableViewDataSource { | |
lazy var tableView: UITableView = { | |
let myTableView = UITableView(frame: view.frame) | |
myTableView.delegate = self | |
myTableView.dataSource = self | |
return myTableView | |
}() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
view = tableView | |
tableView.register(UITableViewCell.self, | |
forCellReuseIdentifier: String(describing: UITableViewCell.self)) | |
} | |
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: UITableViewCell.self), for: indexPath) | |
cell.textLabel?.text = String(describing: T.allCases[indexPath.row]) | |
return cell | |
} | |
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
return T.allCases.count | |
} | |
} | |
enum DNA: DataSourceProtocol { | |
case A,G,C,T | |
} | |
protocol CaseIterable : Hashable { | |
static var allCases: [Self] { get } | |
} | |
protocol DataSourceProtocol: CaseIterable { | |
} | |
extension CaseIterable { | |
static var allCases: [Self] { | |
let anySequence = AnySequence { () -> AnyIterator<Self> in | |
var index = 0 | |
return AnyIterator { | |
let current : Self = withUnsafePointer(to: &index) { | |
return $0.withMemoryRebound(to: self, capacity: 1) { | |
return $0.pointee } } | |
guard current.hashValue == index else { return nil } | |
index += 1 | |
return current | |
} | |
} | |
return Array(anySequence) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment