I can't imagine a delegating downloader class or CLLLocationManager or tableView be without a delegate. So why do we need create it as an optional?
Why do we do
tableview = UITableView()
tableview.delegate = self
tableview.dataSource = self
Why isn't the API made so we could just do:
tableview = UITableView(delegate: self, dataSource: self)
Is this because memory cycles, so we could first nil
either the delegating class or the delegate class and then the other? Is that the only reason?
Even if that's the case, still isn't it just more convenient to make it insatiable using
class tableView{
var delegate: UITableViewDelegate?
var dataSource: UITableViewDataSource?
init(delegate: UITableViewDelegate? = nil, dataSource: UITableViewDataSource?){
self.delegate = delegate
self.dataSource = dataSource
}
}
var tableView = tableView()
Requiring a delegate to be declared on instantiation adds no real benefit to the language itself. It's a convenience that you as the developer could easily add, if you really felt the need, but it doesn't belong in UIKit.
But digging deeper, you wouldn't always want to instantiate the tableview with a delegate anyway. What if the delegate doesn't exist yet? Delegates are not always self
. You may need to build out your tableview with attributes for displaying or implementing at a later point.
You may also want to change the delegate, which for someone reading code, could add a lot of unnecessary obfuscation to debugging. Consider the following pseudo-code:
var tableview = UITableView(delegate:self)
var childController = ChildControllerWithTableView()
childController.prepareForSegue() {
childController.tableview = tableview
childController.tableview.delegate = childcontroller
}
Not only have you changed the delegate, confusing future developers (probably yourself included!) but you also had to (unnecessarily) set the delegate to self
, simply because childController
didn't exist yet.
Or what if the delegator is the delegate, as Josh points out?
var tableview = UITableView(delegate:tableview)
Wait, what? That's not gonna fly!
Still, you can add this to all your projects if you like - if there's a business need (or convenience) reason to do it! It's what makes Swift so awesome:
extension UITableView {
convenience init(delegate: UITableViewDelegate? = nil, dataSource: UITableViewDataSource?){
self.delegate = delegate
self.dataSource = dataSource
}
}
Actually there are several scenarios where you do not need a delegate.
Look at the following screen.
Question
How many elements without its delegate can you find?
Answer
There are 4 UI elements without a delegate:
- A
UITableView
in the top of the screen
- The
UITextField
for the Username
- The
UITextField
for the Password
- A
UITextView
in the bottom of the screen