Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Type-safe Oriented Programming

Type-safe Oriented Programming

Talk da 17ª edição do CocoaHeads RJ sobre Type-safe Oriented Programming

Diego Ventura

April 27, 2016
Tweet

Other Decks in Technology

Transcript

  1. E no início eram os xibs… • XIB - XML

    Interface Builder / Mac OS X Interface Builder • File > New File > View • File’s owner (UIViewController)
  2. E no início eram os xibs… Objective-C Swift [[ViewController alloc]

    initWithNibName:@"ViewController" bundle:nil]; ViewController(nibName: "ViewController", bundle: nil)
  3. E depois veio o Storyboard… • Vários Xibs num mesmo

    arquivo • Set subclass na ViewController • Segues facilitaram a vida dos devs
  4. E depois veio o Storyboard… Objective-C Swift UIStoryboard *storyboard =

    [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil]; YourViewControllerClass *viewController = [storyboard instantiateViewControllerWithIdentifier:@"ViewController"]; ViewController(nibName: "ViewController", bundle: nil)
  5. Strings são ruins • Não possui verificação em compile time

    • Em times grandes, é mais complicado ter uma padronização • Favorece, e muito, o typo! (i.e MyTypoViewControler)
  6. Type-safe w/ Extensions extension UIViewController { private class var nibNameIdentifier:

    String { return NSStringFromClass(self).componentsSeparatedByString(".").last! } class func instantiateFromXib() -> Self { return self.init(nibName: nibNameIdentifier, bundle: nil) } } let welcomeViewController = WelcomeViewController.instantiateFromXib()
  7. Type-safe w/ Extensions and Generics //Register nib let nib =

    UINib(nibName: "MyCustomCellNib", bundle: nil) tableView.registerNib(nib, forCellReuseIdentifier: "MyCustomCellIdentifier") //Dequeue cell var cell = tableView.dequeueReusableCellWithIdentifier(“MyCustomCellIdentifier", forIndexPath: indexPath) as MyCell!
  8. Type-safe w/ Extensions and Generics protocol ReusableViewProtocol { static var

    reuseIdentifier: String { get } } extension ReusableViewProtocol where Self: UIView { static var reuseIdentifier: String { return NSStringFromClass(self) } }
  9. Type-safe w/ Extensions and Generics protocol ReusableNibLoadableProtocol: class { static

    var nibName: String { get } } extension ReusableNibLoadableProtocol where Self: UIView { static var nibName: String { return NSStringFromClass(self).componentsSeparatedByString(".").last! } }
  10. Type-safe w/ Extensions and Generics extension UITableView { func registerClass<T:

    UITableViewCell where T: ReusableViewProtocol>(_: T.Type) { registerClass(T.self, forCellReuseIdentifier: T.reuseIdentifier) } func registerNib<T: UITableViewCell where T: ReusableViewProtocol, T: ReusableNibLoadableProtocol>(_: T.Type) { let bundle = NSBundle(forClass: T.self) let nib = UINib(nibName: T.nibName, bundle: bundle) registerNib(nib, forCellReuseIdentifier: T.reuseIdentifier) } }