---
title: "#2: Chainable Methods 🔗"
url: https://littlebitesofcocoa.com/2-chainable-methods
author: Jake Marsh
published: 2015-05-19
topics: ["Swift","Techniques"]
description: "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..."
---

# #2: Chainable Methods 🔗

By Jake Marsh, May 19, 2015. HTML: https://littlebitesofcocoa.com/2-chainable-methods

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.

``` swift
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:

``` swift
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:

``` swift
Event
  .withCategory(.Meeting)
  .withAttendees([User.me])
  .sort { $0.startDate < $1.startDate }
```

### Chainables TLDR;

- 👆write setters
- 🖖 return `self`
- 🎉 profit
