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()
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:
UITableView
in the top of the screenUITextField
for the UsernameUITextField
for the PasswordUITextView
in the bottom of the screenRequiring 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:
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 becausechildController
didn't exist yet.Or what if the delegator is the delegate, as Josh points out?
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: