Topics

#2: Chainable Methods πŸ”—

Topics

Making functions chainable is quite easy and can allow us to write using an almost DSL-like syntax.

We'll add a new function that does something and then return self. It's that simple.

enum CountdownType: Int { case ToTheSecond, ToTheDay }
enum ColorScheme: Int { case AfterMidnight, ClassyYellow, Tealfish }

class Concern {
  var title: String = ""
  func title(aTitle: String?) -> Concern {
    title = aTitle ?? ""; return self
  }

  var subtitle = ""
  func subtitle(aSubtitle: String?) -> Concern {
    subtitle = aSubtitle ?? ""; return self
  }

  var countdownType: CountdownType = .ToTheSecond
  func countdownType(type: CountdownType) -> Concern {
    countdownType = type; return self
  }

  var colorScheme: ColorScheme = .AfterMidnight
  func colorScheme(scheme: ColorScheme) -> Concern {
    colorScheme = scheme; return self
  }
}

It enables us to write extremely readable and composable code like this:

Concern()
  .title("Big Meeting")
  .subtitle("With those people from that place")
  .countdownType(.ToTheDay)
  .colorScheme(.Tealfish)

Setting properties is just the tip of the iceberg here. Imagine using this technique to create chainable queries:

Event
  .withCategory(.Meeting)
  .withAttendees([User.me])
  .sort { $0.startDate < $1.startDate }

Chainables TLDR;

  • πŸ‘†write setters
  • πŸ–– return self
  • πŸŽ‰ profit