swift-playground
swift-playground copied to clipboard
Syntax Comparison #1: tableView:didSelectRowAtIndexPath:
Thought it would be valuable to give a comparison of common patterns in Cocoa (Touch).
Objective-C
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self.navigationController pushViewController:({
UIViewController *viewController = UIViewController.new;
viewController.view.backgroundColor = UIColor.blueColor;
viewController;
})
animated:YES];
}
Swift
override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
self.navigationController.pushViewController(({
() -> UIViewController? in
var viewController = UIViewController()
viewController.view.backgroundColor = UIColor.whiteColor()
return viewController
})(),
animated: true)
}
Building off of the @cdzombak optionals discussion, we should note that the tableView
and indexPath
parameters are implicitly unwrapped optionals. This will be a common occurence in Swift when briding to older Cocoa APIs with their unsafe nil
-ridden code :wink:
A couple of thoughts, @KevinVitale, to make sure we understand some Swift syntax pecularities:
I’m all for using a Swift closure where we might have used dat C extension. We can ditch the wrapping parens, and we can even simplify the closure:
self.navigationController.pushViewController(({
var viewController = UIViewController()
viewController.view.backgroundColor = UIColor.whiteColor()
return viewController
})(),
animated: true)
Since there are no arguments for the closure, and the compiler can infer the return type, we can just drop the signature stuff.
I believe in this case it will be much more clear to... em... let viewController:
let viewController = UIViewController()
viewController.view.backgroundColor = UIColor.whiteColor()
navigationController.pushViewController(viewController, animated: true)
No doubt that viewController
should be a constant.