Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Syntax Comparison #1: tableView:didSelectRowAtIndexPath: #1

Open
KevinVitale opened this issue Jun 3, 2014 · 4 comments
Open

Syntax Comparison #1: tableView:didSelectRowAtIndexPath: #1

KevinVitale opened this issue Jun 3, 2014 · 4 comments

Comments

@KevinVitale
Copy link
Collaborator

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)
}
@andrewsardone
Copy link
Owner

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 😉

@andrewsardone
Copy link
Owner

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.

@ilyabelikin
Copy link

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)

@andrewsardone
Copy link
Owner

No doubt that viewController should be a constant.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants