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

Protocols and the Promised Land

Michele
January 28, 2016

Protocols and the Promised Land

Swift’s design promotes language features like generics and first-class protocols as key architectural components in application development. However, many of the logical patterns that arise, including ones imported from Objective-C, don’t work as we expect them to. In many cases, Swift’s type system resists certain straightforward patterns, such as constraining a property to both a class and a protocol. This talk will highlight several of these challenges, discuss the underlying causes, and evaluate workarounds.

Michele

January 28, 2016
Tweet

More Decks by Michele

Other Decks in Technology

Transcript

  1. class Fruit {} class Peach: Fruit {} protocol FruitHolder {

    var fruits: [Fruit] { get } } class PeachBasket: FruitHolder { var fruits: [Peach] = [] }
  2. protocol Holder { typealias Item var items: [Item] { get

    } } class PeachBasket: Holder { var items: [Peach] = [] }
  3. protocol Holder { typealias Item var items: [Item] { get

    } } class Basket<Thing>: Holder{ var items: [Thing] = [] func add(item: Thing) { items.append(item) } } class PeachBasket: Basket<Peach> {}
  4. class Basket<Thing: Fruit>: Holder{ var items: [Thing] = [] func

    add(item: Thing) { items.append(item) } }
  5. class Basket<Thing: Fruit>: Holder{ var items: [Thing] = [] func

    add(item: Thing) { items.append(item) } } class FruitBasket: Basket<Fruit> {} class PeachBasket: FruitBasket<Peach> {}
  6. class Bag<Stuff> { class Basket<Thing: Stuff>: Holder{ var items: [Thing]

    = [] func add(item: Thing) { items.append(item) } } }
  7. public protocol ViewControllerProtocol { var view: UIView! { get }

    var storyboard: UIStoryboard? { get } init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) func viewDidLoad() // etc } protocol ThemeableViewController: Themeable, ViewControllerProtocol {} var themedViewController: ThemeableViewController Swift-y but hack-y
  8. var themed: Themeable { get { return self.viewController as! Themeable

    } set(newThemeable) { if let themedViewController = newThemeable as? UIViewController{ viewController = themedViewController } } } var viewController: UIViewController init<T where T: Themeable, T: UIViewController>(viewController: T) { self.viewController = viewController } Also swfit-y also hack-y