I would like some opinions on a idea I just had :
I have a bunch of UITableViewCell
subclass. In my particular case it's just to add a UISwitch
and have a property to access it.
Setting the switch's value is straight forward. Updating the Bool associated to this switch not so much.
I thought of adding a closure as a property of my cell so that I can just call it to update my bool in my UITableViewController
subclass
Here is some the code I thought of :
class SwitchTableViewCell:UITableViewCell {
@IBOutlet var theSwitch:UISwitch!
var switchValueChangedBlock:((Bool) -> Void)?
override func awakeFromNib() {
theSwitch.addTarget(self, action: "switchValueChanged", forControlEvents: .ValueChanged)
}
deinit {
theSwitch.removeTarget(self, action: nil, forControlEvents: .AllEvents)
}
func setCallback(callback:(Bool) -> Void) {
switchValueChangedBlock = callback
}
func switchValueChanged() {
switchValueChangedBlock?(theSwitch.on)
}
}
class myTableViewController:UITableViewController {
var alarmEnabled:Bool = true
...
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell?
if indexPath.section == enableSection {
cell = tableView.dequeueReusableCellWithIdentifier(enableAlarmCellIdentifier,forIndexPath: indexPath)
let myCell = cell as! SwitchTableViewCell
myCell.theSwitch.on = alarmEnabled
myCell.setCallback({[unowned self] (boolValue:Bool) in
self.alarmEnabled = boolValue
})
}
}
...
}
As advantages I see following :
I can't grasp the possible drawbacks my idea could have and if in overall it's a bad or a good idea.
Personally I am kinda old school and simply prefer the delegation pattern over closures.
But for your question ... what you suggest is exactly what closures are made for. Just go for it.
You simply hand over to another class' object some piece of code (or the reference to some subroutine's entry point respectively) that you want to be executed when some event occours. That's what it's made for and that's what you are doing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With