TableViewのdataSourceはoptionalにすべきかemptyにすべきか。
結論から言うとemptyで扱ったほうがコードがすっきりして良いとのこと。
コードを並べてみます。
1.dataSourceをoptionalにした場合
class OptionalDataSourceViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
//ここをOptional定義
var dataSource:[Data]?{
didSet{
tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
fetchData()
tableView.alpha = 0.0
}
}
extension OptionalDataSourceViewController: UITableViewDelegate{
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource?.count ?? 0
}
}
extension OptionalDataSourceViewController: UITableViewDataSource{
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell")
cell?.textLabel!.text = dataSource?[indexPath.row].name
return cell!
}
}
private extension OptionalDataSourceViewController{
func fetchData(){
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Double(NSEC_PER_SEC))),dispatch_get_main_queue()){
self.dataSource = [Data(name: "data1"),Data(name: "data2")]
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.tableView.alpha = 1.0
})
}
}
}
2.dataSourceをemptyにした場合
class EmptyDataSourceViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
//ここをEmpty定義
var dataSource:[Data] = [Data](){
didSet{
tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
fetchData()
tableView.alpha = 0.0
}
}
extension EmptyDataSourceViewController: UITableViewDelegate{
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
}
extension EmptyDataSourceViewController: UITableViewDataSource{
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell")
cell?.textLabel!.text = dataSource[indexPath.row].name
return cell!
}
}
private extension EmptyDataSourceViewController{
func fetchData(){
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Double(NSEC_PER_SEC))),dispatch_get_main_queue()){
self.dataSource = [Data(name: "data1"),Data(name: "data2")]
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.tableView.alpha = 1.0
})
}
}
}
dataSourceをOptionalにしてしまうと、当然アクセスするときにnilかどうかを意識したコードを書かないといけないです。emptyで定義した方がスッキリしてよさげです。これからは迷わずempty定義していこうと思います。
ちょっとしたtipsですが、dataSourceのdidSetにreloadData()仕込むのは良いやり方ですね。
参考)
iOS: An Optional vs Empty Data Source in Swift
Optional vs Empty Table Views in Swift