Skip to content

Instantly share code, notes, and snippets.

@mironal
Created April 20, 2016 00:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mironal/d640c57e06ce2f644137e8dc182e1256 to your computer and use it in GitHub Desktop.
Save mironal/d640c57e06ce2f644137e8dc182e1256 to your computer and use it in GitHub Desktop.
UITableView の Section を Swift の enum を使っていい感じに記述する方法
import UIKit
import XCPlayground
class ViewController: UITableViewController {
enum Section: Int {
case Animals = 0
case Foods
}
let animals = ["Dog", "Cat"]
let foods = ["Apple", "Banana"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: String(UITableViewCell))
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch Section(rawValue: section) {
case .Some(.Animals):
return animals.count
case .Some(.Foods):
return foods.count
case .None:
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// いきなり switch case せずに guard を使って早期リターンする場合の書き方
// 以降の処理が複雑になる場合はネストが深くならないのでこっちのほうがいいかも
guard let s = Section(rawValue: indexPath.section) else {
// クラッシュする
return tableView.dequeueReusableCellWithIdentifier("Undefined Section", forIndexPath: indexPath)
}
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(String(UITableViewCell), forIndexPath: indexPath)
switch s {
case .Animals:
cell.textLabel?.text = animals[indexPath.row]
case .Foods:
cell.textLabel?.text = foods[indexPath.row]
}
return cell
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch Section(rawValue: section) {
case .Some(.Animals):
return "動物たち"
case .Some(.Foods):
return "食べ物たち"
case .None:
return "Undefined"
}
}
}
let vc = ViewController(style: .Grouped)
XCPlaygroundPage.currentPage.liveView = vc.view
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment