swift-playground icon indicating copy to clipboard operation
swift-playground copied to clipboard

Syntax Comparison #1: tableView:didSelectRowAtIndexPath:

Open KevinVitale opened this issue 10 years ago • 4 comments

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)
}

KevinVitale avatar Jun 03 '14 15:06 KevinVitale

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:

andrewsardone avatar Jun 04 '14 01:06 andrewsardone

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.

andrewsardone avatar Jun 04 '14 01:06 andrewsardone

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)

ilyabelikin avatar Jun 05 '14 13:06 ilyabelikin

No doubt that viewController should be a constant.

andrewsardone avatar Jun 05 '14 13:06 andrewsardone