---
title: "Libraries bites - Little Bites of Cocoa"
description: "Little Bites of Cocoa about Libraries: short tips and techniques for iOS and Mac development, each a brief explanation of one concept, technique or tool."
url: "https://littlebitesofcocoa.com/topics/7-libraries"
author: "Jake Marsh"
---
# Bites about: [Libraries](https://littlebitesofcocoa.com/topics/7-libraries)

Topics

- [Libraries](https://littlebitesofcocoa.com/topics/7-libraries)

## [#304: Simple Sound Playback with SwiftySound 🔊](https://littlebitesofcocoa.com/304-simple-sound-playback-with-swiftysound)

 Wednesday March 22nd, 2017

Topics

- [Libraries](https://littlebitesofcocoa.com/topics/7-libraries)

**Apple** ships [a ton of great APIs](https://littlebitesofcocoa.com/topics/55-audio) for playing *audio* in our **apps**.

They offer a wealth of great *functionality*, but also a fair amount of *complexity*.

Often we don't need all that power. Perhaps we're adding sound effects or audio feedback to one of our user interfaces, or maybe we just need to loop some background music in the menu of our video game.

Today we'll check out a new library from [Adam Cichy](https://github.com/adamcichy) called [SwiftySound](https://github.com/adamcichy/SwiftySound) that can help us simplify our *audio* playback code. Let's take a look.

First up, simple playback:

```swift
Sound.play(file: "unscheduled-offworld-activation.wav")
```

or

```swift
Sound.play(url: someURL)
```

That's it. Yes, really.

This kind of **`UIImage`**-esque simplicity has always been sort of missing from **UIKit**. Neat to see.

[SwiftySound](https://github.com/adamcichy/SwiftySound) doesn't stop there though, We can easily loop *sounds*:

```swift
Sound.play(file: "main-menu", fileExtension: "wav", numberOfLoops: -1)
```

We could pass in any `Int` here to loop the music, but we've passed `-1` to indicate we want to loop forever.

One of the most useful features of [SwiftySound](https://github.com/adamcichy/SwiftySound) is the inclusion of a `UserDefaults`-persisted flag for persisting the user's preference of sound playback being enabled or disabled.

We can use this on our **app's Settings screen** to allow users to easily enable/disable sound effects globally.

```swift
Sound.enabled = soundsSwitch.on
```

The value is then automatically persisted and respected across app launches. A nice touch by [SwiftySound](https://github.com/adamcichy/SwiftySound)'s author, [Adam Cichy](https://github.com/adamcichy).

We're not required to use this [singleton](https://littlebitesofcocoa.com/4-singletons) `Sound` instance by the way, we can always create a `Sound` instance and pass it around:

```swift
let sound = Sound(url: soundEffectURL)
```

Then later:

```swift
sound.play()
```

Last but not least, [SwiftySound](https://github.com/adamcichy/SwiftySound) stands out for being [a single **Swift** file](https://github.com/adamcichy/SwiftySound/blob/master/Classes/Sound.swift).

It's great to see this kind of power *and* flexibility in such a tiny little **dependency**.

😍 More like this please!

Full documentation for *SwiftySound* is at [git.io/swiftysound](https://git.io/swiftysound)

Topics

- [Libraries](https://littlebitesofcocoa.com/topics/7-libraries)
- [UIKit](https://littlebitesofcocoa.com/topics/1-uikit)

## [#299: Building Better Forms with UITextField-Navigation 🗺](https://littlebitesofcocoa.com/299-building-better-forms-with-uitextfield-navigation)

 Monday February 27th, 2017

Topics

- [Libraries](https://littlebitesofcocoa.com/topics/7-libraries)
- [UIKit](https://littlebitesofcocoa.com/topics/1-uikit)

Building great forms for users to enter information on iOS is tough. There's a lot of small details which are easy to get wrong. Today we'll begin looking at ways to improve this process.

First up, is **navigation**. 📍

Allowing for quick and simple navigation from one **form field** to the next can *dramatically* reduce friction for our users.

We'll use a great new library from [Thanh Pham](https://github.com/T-Pham) called [UITextField-Navigation](https://github.com/T-Pham/UITextField-Navigation) to pull this off. Let's get started.

[UITextField-Navigation](https://github.com/T-Pham/UITextField-Navigation) is built around the concept of telling each **field** which **field** should be *"next"* in the form.

Once we've done that for all of our fields, the library takes over and displays a navigation bar above the keyboard automatically:

![Image 1 of 4 from bite #299: Building Better Forms with UITextField-Navigation](https://media.littlebitesofcocoa.com/bite-assets/299-1.png)

We can set up these relationships *super* easily in in **Interface Builder**:

![Image 2 of 4 from bite #299: Building Better Forms with UITextField-Navigation](https://media.littlebitesofcocoa.com/bite-assets/299-2.png)

...or in code:

```swift
let nameTextField = UITextField()
let bioTextView = UITextView()

nameTextField.nextNavigationField = bioTextView
```

Now, whenever a user begins editing a `UITextField` or `UITextView` in our app, a **navigation toolbar** will automatically be shown above the **keyboard**:

![Image 3 of 4 from bite #299: Building Better Forms with UITextField-Navigation](https://media.littlebitesofcocoa.com/bite-assets/299-3.gif)

We can use `UIAppearance` to completely customize the look and feel of the **toolbar**:

```swift
NavigationFieldToolbar.appearance().barStyle = .black
NavigationFieldToolbar.appearance().backgroundColor = UIColor.purple
NavigationFieldToolbarButtonItem.appearance().tintColor = UIColor.white
```

![Image 4 of 4 from bite #299: Building Better Forms with UITextField-Navigation](https://media.littlebitesofcocoa.com/bite-assets/299-4.png)

Last but not least, we aren't limited to a *"standard"* set of buttons/items in the **toolbar**.

We'll use the `navigationFieldToolBar` optional **property** that the library adds to `UITextField` and `UITextView` to first customize some individual **properties** directly:

```swift
guard let toolbar = nameTextField.navigationFieldToolbar else { return }

toolbar.barStyle = .default
toolbar.backgroundColor = UIColor.red
toolbar.previousButton.title = "Backward!"
toolbar.nextButton.title = "Onward!"
toolbar.doneButton.title = "Dismiss"
```

...then create our own array of **toolbar** items:

```swift
let expandButton = UIBarButtonItem(
  title: "Expand",
  style: .plain,
  target: self,
  action: #selector(expandForm)
)

let flexible = UIBarButtonItem(
  barButtonSystemItem: .flexibleSpace,
  target: nil,
  action: nil
)

toolbar.items = [
  toolbar.previousButton,
  toolbar.nextButton,
  flexible,
  expandButton,
  flexible,
  toolbar.doneButton
]
```

Neat!

Learn more about [UITextField-Navigation](https://github.com/T-Pham/UITextField-Navigation) at [git.io/textfieldnav](http://git.io/textfieldnav).

Topics

- [Libraries](https://littlebitesofcocoa.com/topics/7-libraries)
- [Foundation](https://littlebitesofcocoa.com/topics/6-foundation)

## [#295: Building an API client with Sourcery Key/Value Annotations 🔮](https://littlebitesofcocoa.com/295-building-an-api-client-with-sourcery-key-value-annotations)

 Friday February 10th, 2017

Topics

- [Libraries](https://littlebitesofcocoa.com/topics/7-libraries)
- [Foundation](https://littlebitesofcocoa.com/topics/6-foundation)

In [Bite #294](https://littlebitesofcocoa.com/294-annotations-with-sourcery) we learned about **annotations** in [Sourcery](https://github.com/krzysztofzablocki/Sourcery). They're a great way to make extra metadata available on our types when accessing them in [Sourcery](https://github.com/krzysztofzablocki/Sourcery)'s `.stencil` templates.

Today we'll take a look at one of the most powerful features of **annotations** in [Sourcery](https://github.com/krzysztofzablocki/Sourcery), ***Key/Value Annotations***.

We'll explore these by building a fictional API client powered by a simple **Swift Enum**. Let's begin!

First, we'll need to create our **enum**. Then, we'll define some **cases** to represent each **HTTP endpoint** we want to be able to call.

For us, these are a classic set of *"get all"*, *"get one"*, *"create"*, *"change"*, and *"delete"*:

```swift
enum SpaceshipsAPI {
    case ships
    case ship(shipID: Int)
    case createShip(shipID: Int, ship: Ship)
    case updateShip(shipID: Int, ship: Ship)
    case deleteShip(shipID: Int)
}
```

Long-time readers may recognize this **enum** technique from *Bites* such as [#93](https://littlebitesofcocoa.com/93-creating-a-router-for-alamofire) or [#150](https://littlebitesofcocoa.com/150-standardizing-network-abstractions-with-moya).

Here's where the magic begins though. 🎩

[Sourcery](https://github.com/krzysztofzablocki/Sourcery) *Key/Value Annotations* are similar to regular **Annotations**. Instead of a simple tag though, they allow us to annotate types, enums, enum cases, etc with a set of names and a values.

*Key/Value Annotations* work everywhere that regular **Annotations** do. We can annotate types, enums, enum cases, and more.

They look like this:

```swift
/// sourcery: key = value
/// sourcery: anotherKey = someOtherValue
```

They can also be listed in a single line:

```swift
/// sourcery: key = value, anotherKey = someOtherValue
```

Values can contain some basic types:

```swift
/// sourcery: maxSpeed = 1500, hasHyperdrive = true
/// sourcery: codename = "blacksaber"
```

Ok, back to our API client. Now that we know we can add simple metadata like this above things in our code, let's use this technique to describe each API endpoint.

```swift
enum SpaceshipsAPI {
    /// sourcery: method = "GET", path = "/spaceships"
    /// sourcery: timeout = 5
    case ships
    ...
}
```

Nice! Normally, we might put things like `method` and `path` into essentially a big `switch` statement `switch`ing on `self`, and returning the correct `method` or `path`.

With [Sourcery](https://github.com/krzysztofzablocki/Sourcery) *Key/Value Annotations* though, we can let [Sourcery](https://github.com/krzysztofzablocki/Sourcery) *generate* all of these statements for us.

Let's create a `SpaceshipsAPI+Properties.stencil` template that extends our `enum`, generating the **computed properties**:

```swift
extension SpaceshipsAPI {
  public var path: String? {
    switch self {
      {% for c in type.SpaceshipsAPI.cases %}
      {% if c.annotations.path %}
      case .{{ c.name }}: return "{{c.annotations.path}}"
      {% endif %}
    {% endfor %}
    default: return nil
    }
  }

  // ... etc
}
```

Success! Now we can work at a much higher level. We can update our **annotations** and never need to manually edit tedious `switch` statements.

We'll [run sourcery](https://littlebitesofcocoa.com/292-metaprogramming-with-sourcery), which creates/updates `SpaceshipsAPI+Properties.generated.swift`, filling it with all those beautiful switches.

Finally, we can use our new **properties** like this:

```swift
  print(SpaceshipsAPI.ships.path)
```

The use cases can begin to boggle the mind a bit here.

We can now add *rich metadata* to just about anything in our **Swift** code. Then use it to [metaprogram](https://en.wikipedia.org/wiki/Metaprogramming) *new* **Swift** code that we can use in our **project**.

Neat!

Topics

- [Libraries](https://littlebitesofcocoa.com/topics/7-libraries)

## [#294: Annotations with Sourcery 🔮](https://littlebitesofcocoa.com/294-annotations-with-sourcery)

 Wednesday February 8th, 2017

Topics

- [Libraries](https://littlebitesofcocoa.com/topics/7-libraries)

We first covered [Sourcery](https://github.com/krzysztofzablocki/Sourcery) back in [Bite #292](https://littlebitesofcocoa.com/292-metaprogramming-with-sourcery). It's a command-line tool that helps us generate **Swift** code from `.stencil` template files.

Today we'll check a specific feature of [Sourcery](https://github.com/krzysztofzablocki/Sourcery), **annotations**. Let's dive in.

Nefore we begin, let's do a quick "refresher". The **TLDR** for [Sourcery](https://github.com/krzysztofzablocki/Sourcery) is *Render template files into real Swift code. Full access to the type system using [SourceKitten](https://github.com/jpsim/SourceKitten). Useful for simple things (automate tasks like adding counts to enums), or crazy complex things (automatically generate Swift test code). Essentially, [metaprogramming](https://en.wikipedia.org/wiki/Metaprogramming).* Whew. Ok, moving on.

**Annotations** are simply small bits of metadata that *annotate* our properties functions, enums, enum cases and other types.

Then, later we can access this metadata inside our `.stencil` template files.

Let's try it out.

Before we begin, let's add a new **Swift Enum** to our project. Nothing special here so far, just regular **Swift**.

```swift
enum SpaceshipKind {
    case cruiser
    case frieghter
    case destroyer
}
```

Next, we'll add a new `SpaceshipKind+Count.stencil` file for Sourcery to render. We'll use the *"Empty"* option in **Xcode** when creating a new file, then open the **Inspector** (right side) and change the **file's type** to *Swift Source* so it will read (slightly) nicer in **Xcode**.

Finally, let's run `sourcery`:

```shell
sourcery source/ templates/ /source/_generated/ --watch --verbose
```

Passing in the `--watch` tells [Sourcery](https://github.com/krzysztofzablocki/Sourcery) to run continuously and re-render our templates anytime our code or templates change. Neat.

The `--verbose` flag tells [Sourcery](https://github.com/krzysztofzablocki/Sourcery) to print a bunch of useful debug info to the console while it's working. Helpful at first, but once we're more comfortable with [Sourcery](https://github.com/krzysztofzablocki/Sourcery), we can probably leave this off.

Whew! Now we can [finally](https://twitter.com/applefinally) start using **Annotations**.

Let's add an **annotation** to our enum:

```swift
enum SpaceshipKind {
    case cruiser
    case frieghter
    case destroyer
}
```

Then in our template, let's generate a `count` property for all our enums:

```swift
{% for enum in types.enums %}
extension {{ enum.name }} {
  static var count: Int { return {{ enum.cases.count }} }
}
{% endfor %}
```

This works great:

```swift
extension SpaceshipKind {
  static var count: Int { return 3 }
}
```

But what if we were farther along in our project? What if we had *many* more **Enums** in our code base, and wanted to exempt a few of them from generating a count property.

We'll add another new enum:

```swift
enum EngineKind {
    case hyperdrive
    case sunsail
}
```

Since we added some code, Sourcery's `--watch` kicks in and re-generates our template:

```swift
extension SpaceshipKind {
  static var count: Int { return 3 }
}
extension EngineKind {
  static var count: Int { return 2 }
}
```

Let's pretend we don't need that second enum to get a count property.

There's a few ways we could approach this in [Sourcery](https://github.com/krzysztofzablocki/Sourcery), but this gives us a nice way to learn about and understand how **annotations** work.

We'll add one above `EngineKind` in our code:

```swift
/// sourcery: skipCount
enum EngineKind {
    case hyperdrive
    case sunsail
}
```

**Annotations** are simply special comments that [Sourcery](https://github.com/krzysztofzablocki/Sourcery) parses, and makes available in our `.stencil` templates.

The cool part is it's location aware, so we can put **annotations** above types, and they'll be available on those types in our `.stencil` templates! Same goes for **annotations** on **properties**, **enum cases** and more!

Now, we can access this **annotation** in our template:

```swift
{% for enum in types.enums %}
extension {{ enum.name }} {
  {% ifnot enum.annotations.skipCount %}
  static var count: Int { return {{ enum.cases.count }} }
  {% endif %}
}
{% endfor %}
```

Finally, our generated code is back to just the one **enum**:

```swift
extension SpaceshipKind {
  static var count: Int { return 3 }
}
```

Success!

We can also apply **annotations** to multiple things at once using `:begin` and `:end` tags:

```swift
/// sourcery:begin: skipCustomSetter
var captainID: Int
var maxSpeedInParsecs: Int
/// sourcery:end
```

This is just the beginning. Come back next time to learn about key/value pair **annotations**.

Learn more about [Sourcery](https://github.com/krzysztofzablocki/Sourcery) at [git.io/sourcery](https://git.io/sourcery) (also in [Bite #292](https://littlebitesofcocoa.com/292-metaprogramming-with-sourcery))

Topics

- [Libraries](https://littlebitesofcocoa.com/topics/7-libraries)
- [Foundation](https://littlebitesofcocoa.com/topics/6-foundation)

## [#293: Modern Attributed Strings with Attributed 🖋](https://littlebitesofcocoa.com/293-modern-attributed-strings-with-attributed)

 Monday February 6th, 2017

Topics

- [Libraries](https://littlebitesofcocoa.com/topics/7-libraries)
- [Foundation](https://littlebitesofcocoa.com/topics/6-foundation)

`AttributedString`s are a wonderful way for us to describe and add **rich**, ***styled*** text to our apps.

We've covered a few different [approaches](https://littlebitesofcocoa.com/143-declarative-attributed-strings-with-bonmot) and [solutions](https://littlebitesofcocoa.com/274-swifty-attributed-strings-with-swiftyattributes) for composing `AttributedString`s over the years.

Today we'll check out at a new library, [Attributed](https://github.com/Nirma/Attributed) by [Nicholas Maccharoli](https://github.com/Nirma), which stands out as a modern approach to the task. Let's take a look.

We'll start by looking at the "standard" way to use `AttributedString`s in **Foundation**:

```swift
let font = UIFont(name: "AvenirNext", size: 18.0)!

NSAttributedString(string: "Han Solo", attributes: [
  NSForegroundColorAttributeName: UIColor.black,
  NSFontAttributeName: font
])
```

Not too bad, but we can do better. Let's try this same thing but with [Attributed](https://github.com/Nirma/Attributed):

```swift
"Han Solo".attributed(with: Attributes { $0.foreground(color: .black).font(font) })
```

Neat!

*"Why not just use the `AttributedString` API that ships with **Foundation**?"*

This is a fair question.

Imagine building an app that had many different attributed string styles. With [Attributed](https://github.com/Nirma/Attributed), we're given a strongly API, allowing us to omit a couple of types. We're also able to omit the long, verbose key names.

Finally, (and perhaps most importantly) we're using a sort of "closure composition" technique.

This involves accepting a **Swift closure** in an `initializer`, giving us the anonymous argument `$0` to play with. Then, we can chain `function` calls on to `$0` to add attributes.

All of this leads to a dramatic decrease in manual typing (even with autocomplete in **Xcode**, writing tons of attribute collections stops being fun, quickly).

It also allows us to work more effeciently, and accurately. We can lean on our syntactic shorthand and trust in the Swift's type system to get us to the finish line.

## Inheritance

Before we go, let's talk about one of the most common hiccups we can run into when writing `AttributedString`-related code. **Inheritance.**

We've all been there. We're composing an `AttributedString` to go into a `UILabel`. We're pumped because we've got the style neatly translated from the original design into code. Then we see it. The design calls for one of the words in the label to be a different color, for emphasis.

Dun, dun dun.

No worries though, with [Attributed](https://github.com/Nirma/Attributed) we can solve this problem quickly:

```swift
let base = Attributes().font(UIFont(name: "AvenirNext", size: 18.0)!)

let highlighted = base.foreground(color: .red)

"Han Solo is the captain of the ".attributed(with: base)
    + "Millennium Falcon".attributed(with: highlighted)
```

Very cool. We're able to define a base set of attributes in `Attributes()`, then compose new sets that inherit all the attributes of our **base** set.

Then, we're leaning on [Attributed](https://github.com/Nirma/Attributed)'s extension to `String` and `String`'s support of the `+` operator to write some *super* clean code.

***Pro Tip:*** This functionality also allows us to easily build up a re-usable set of `Attributes()`, keeping them in one spot, then sprinkling them throughout our code.

Learn more about [Attributed](https://github.com/Nirma/Attributed) at [git.io/attributed](http://git.io/attributed).

Topics

- [Libraries](https://littlebitesofcocoa.com/topics/7-libraries)
- [Tools](https://littlebitesofcocoa.com/topics/9-tools)

## [#292: Metaprogramming with Sourcery 🔮](https://littlebitesofcocoa.com/292-metaprogramming-with-sourcery)

 Friday January 20th, 2017

Topics

- [Libraries](https://littlebitesofcocoa.com/topics/7-libraries)
- [Tools](https://littlebitesofcocoa.com/topics/9-tools)

We cover plenty of libraries and developer tools here on *LBOC*. Many are useful not just on their surface, but also in terms of how they allow us to *learn* from our fellow developers.

Through this process, we collectively explore new approaches and techniques. New ideas emerge all the time.

Every now and then, one of these ideas stands out.

Sometimes, an idea makes too much sense, or is simply too useful to ignore.

In modern times, things like [Fastlane](https://fastlane.tools/), [CocoaPods](https://cocoapods.org/), and [Carthage](https://github.com/Carthage/Carthage) come to mind. Slightly more seasoned folks may remember the emergence of [Pull to Refresh](https://en.wikipedia.org/wiki/Pull-to-refresh), or [BWToolkit](http://brandonwalkin.com/bwtoolkit/).

[Sourcery](https://github.com/krzysztofzablocki/Sourcery) from [Krzysztof Zabłocki](https://github.com/krzysztofzablocki) is the latest addition to this set.

It brings the concept of "[meta-programming](https://en.wikipedia.org/wiki/Metaprogramming)" to Swift, and it is definitely too useful to ignore.

Let's peer into our crystal ball, and see what it can do.

At its core, [Sourcery](https://github.com/krzysztofzablocki/Sourcery) generates **Swift** code from **template files**.

It elegantly brings together two other great developer tools: [SourceKitten](https://github.com/jpsim/SourceKitten) (for introspecting our code), and [Stencil](https://github.com/kylef/Stencil) (for templates).

It aims to solve a few problems:

- Reduce time spent writing so-called "boilerplate", or repetitive/obvious code.
- Provide a way to reason about the types in our code, and their properties.
- Reduce simple human errors, caused by things like typos.

Ok, enough introduction. Here's how [Sourcery](https://github.com/krzysztofzablocki/Sourcery) works:

- First, we'll write some code that looks *almost* like regular **Swift** code into "template" (`.stencil`) files.
- Then, we'll run the `sourcery` command-line tool. This will "render" our `.stencil` files into `.swift` files that we'll add to our project.
- Finally, when we build our app, our "generated" `.swift` files will get compiled just like any other `.swift` files we might add.

Immediately some ideas of how to use this begin coming to mind. Here's a few specific tasks that might cause us to reach for [Sourcery](https://github.com/krzysztofzablocki/Sourcery):

- Conforming our types to `NSCoding`.
- Conforming to `Equatable` or `Hashable`
- Writing JSON de-serialization code

Maintaining each of these implementations is a never-ending task. Anytime we add, remove, or change a property we'll need to potentially revist each of these bits of code as well. Bummer.

Ok. Let's try this thing.

First we'll need to get the `sourcery` command-line tool. The simplest way to do this is to [download the latest release binary here](https://github.com/krzysztofzablocki/Sourcery/releases).

Let's `cd` into the root directory of the download and copy the tool over to somewhere permanent:

```shell
cp bin/sourcery /usr/local/bin
```

(Note: /usr/local/bin is a common place to put command line tools on **macOS** thanks largely to the fact that [Homebrew](http://brew.sh/) puts things there, so it's likely already in our `$PATH`).

Neat. Now we can use it anywhere.

We could also have simply copied the tool into our project, and added it to source control. Any approach is fine, we just need to be able to run it in the root directory of our project somehow.

Now, let's head into that root directory of our project, and create a couple directories:

```shell
mkdir templates
mkdir generated
```

We're almost ready to try things out. First though, we'll need a template to generate from.

Let's add a new file in the `templates` directory called `Enum+Count.stencil`. Then, we'll write our first template code:

```swift
{% for enum in types.enums %}
extension {{ enum.name }} {
  static var count: Int { return {{ enum.cases.count }} }
}
{% endfor %}
```

The `{{`'s, `}}`'s, `{%`'s, and `%}`'s are [Stencil](https://github.com/kylef/Stencil) template tags.

[Stencil](https://github.com/kylef/Stencil) deserves a full *Bite* of it's own, but for now we just need to know that statements within these tags get evaluated by the `sourcery` command line tool, and iterated or replaced when generating **Swift** code.

The rest of the content is regular **Swift** code.

Anyone who has worked on a web app in recent years should feel right at home with this technique. Instead of generating HTML though, we're generating **Swift** code, neat!

Let's break down what's happening in our template:

First, we want to iterate through all the `enums` in our project's code:

```swift
{% for enum in types.enums %}

{% endfor %}
```

Then, for each `enum` we find, we want to extend it to have a new `static` property called `count`.

```swift
extension {{ enum.name }} {
  static var count: Int { return {{ enum.cases.count }} }
}
```

This property will return the number of `cases` in the `enum`. (Providing us a piece of functionality currently missing from Swift itself).

Finally, we can run `sourcery`.

```shell
./sourcery . templates generated --watch
```

We've passed in the `--watch` flag to make `sourcery` watch our template files, and re-generate them anytime it sees a change. Neat.

This will scan our source code for a bit, then produce a new file in the `generated` directory called `Enum+Count.generated.swift`.

It will look like this:

```swift
extension SpaceshipKind {
  static var count: Int { return 37 }
}

extension CrewRank {
  static var count: Int { return 10 }
}

extension HTTP.Method {
  static var count: Int { return 7 }
}
```

![Image 1 of 2 from bite #292: Metaprogramming with Sourcery](https://media.littlebitesofcocoa.com/292-1.jpg)

*How cool is that?*

Now, we just need to add this generated file to our Xcode project like we would any other file. Its contents will be replaced anytime `sourcery` runs.

**Pro Tip:** We can also optionally add a new *"Run Script..."* Build Phase to our Xcode project to run the `sourcery` command (without `--watch` of course) at the beginning of each build of our app. Very cool.

The [Sourcery](https://github.com/krzysztofzablocki/Sourcery) Github repo offers a some very useful example templates for adding things like [Equatable](https://github.com/krzysztofzablocki/Sourcery/blob/master/Templates/AutoEquatable.stencil) and [Hashable](https://github.com/krzysztofzablocki/Sourcery/blob/master/Templates/AutoHashable.stencil). These examples are a great way to learn more about what's possible.

We've of course only barely scratched the surface of what's possible with [Sourcery](https://github.com/krzysztofzablocki/Sourcery). Look out for future Bites where we'll explore much more...

![Image 2 of 2 from bite #292: Metaprogramming with Sourcery](https://media.littlebitesofcocoa.com/292-2.gif)

Learn more and find full documentation of [Sourcery](https://github.com/krzysztofzablocki/Sourcery) at [git.io/sourcery](https://git.io/sourcery)

Topics

- [Libraries](https://littlebitesofcocoa.com/topics/7-libraries)
- [Testing](https://littlebitesofcocoa.com/topics/58-testing)

## [#291: Running Multiple UI Tests at Once with Bluepill 💊](https://littlebitesofcocoa.com/291-running-multiple-ui-tests-at-once-with-bluepill)

 Thursday January 19th, 2017

Topics

- [Libraries](https://littlebitesofcocoa.com/topics/7-libraries)
- [Testing](https://littlebitesofcocoa.com/topics/58-testing)

We've covered UI Tests [a](https://littlebitesofcocoa.com/30-ui-testing) [fair](https://littlebitesofcocoa.com/129-more-ui-testing-tips) [amount](https://littlebitesofcocoa.com/124-more-on-ui-testing) over the years, but one thing has always stuck out: Running tests can be slow. *Very slow.*

Even if our individual tests themselves run quickly, the entire process is essentially "single threaded", slow to start up and complete each pass, and is prone to strange errors.

Today we'll take a look at [Bluepill](https://github.com/linkedin/bluepill), a new tool from [LinkedIn](https://github.com/linkedin) that can help us with all of this by running multiple **iOS Simulators** in parallel, simultaneously. Let['](http://matrix.wikia.com/wiki/Redpill)s dive in[.](https://www.youtube.com/watch?v=zE7PKRjrid4)

We'll start by cloning the repository, then running the build script that comes inside:

```shell
./build.sh
```

This will build the command line tool. Once it's finsihed, we can copy the tool somewhere permanent:

```shell
cp build/Build/Products/Debug/bp /usr/local/bin
```

Then rename it to something we can more easily identify:

```shell
mv /usr/local/bin/bp /usr/local/bin/bluepill
```

(Note: `/usr/local/bin` is a common place to put command line tools on macOS thanks largely to the fact that [Homebrew](http://brew.sh/) puts things there, so it's likely already in our `$PATH`).

Now that we have [Bluepill](https://github.com/linkedin/bluepill) installed, let's try it out.

We can head back to our project and run something like:

```shell
./bluepill -a ./Spaceships.app -s ./SpaceshipsUITests.xcscheme -o ./output/
```

This is great for quick runs, but ideally we'd be able to configure this sort of thing once and use it each time. Let's make a quick configuration file using `JSON`. We'll call it `bluepill-config.json`:

```json
{
   "app": "./Spaceships.app",
   "scheme-path": "./SpaceshipsUITests.xcscheme",
   "output-dir": "./bluepill-logs/"
}
```

By default [Bluepill](https://github.com/linkedin/bluepill) will run `4` iOS Simulators simultaneously. Before we run our tests, let's turn that up a notch by adding one more option to our config file:

(This will cause our test to be run in up to ***12* iOS Simulators** at once. Very cool).

```json
{
   "app": "./Spaceships.app",
   "scheme-path": "./SpaceshipsUITests.xcscheme",
   "output-dir": "./bluepill-logs/",
   "num-sims": 12
}
```

Finally, we can start our engines:

```shell
./bluepill -c bluepill-config.json
```

![Image from bite #291: Running Multiple UI Tests at Once with Bluepill](https://media.littlebitesofcocoa.com/291-1.gif)

So awesome.

Not only are we saving tons of time this way, but [Bluepill](https://github.com/linkedin/bluepill) also does other helpful things for us, such as automatically retrying when the Simulator hangs or crashes. Neat.

We've only scratched the surface of what's possible with [Bluepill](https://github.com/linkedin/bluepill). Be sure to check out the [README](https://github.com/linkedin/bluepill) for a full list of options and defaults.

Learn more about [Bluepill](https://github.com/linkedin/bluepill) at [git.io/bluepill](https://git.io/bluepill).

Topics

- [Libraries](https://littlebitesofcocoa.com/topics/7-libraries)

## [#290: Monitoring Performance with GDPerformanceView 📈](https://littlebitesofcocoa.com/290-monitoring-performance-with-gdperformanceview)

 Tuesday January 17th, 2017

Topics

- [Libraries](https://littlebitesofcocoa.com/topics/7-libraries)

Optimizing for responsiveness is a huge part of making great apps. Before we can optimize though, we'll need to measure. **Xcode** and **Instruments** offer some incredible tools to do "deep-dives" for answers ([Bite #68](https://littlebitesofcocoa.com/68-time-profiler-basics), [Bite #113](https://littlebitesofcocoa.com/113-profiling-core-animation)), but often we just want to keep an eye on our app's performance and respond as needed.

Today we'll try out a library called [GDPerformanceView](https://github.com/dani-gavrilov/GDPerformanceView-Swift) by [Gavrilov Daniil](https://github.com/dani-gavrilov) that lets us easily monitor our app's **rendering speed** and **CPU usage** in the device's status bar while we use the app. Let's begin.

We'll install [GDPerformanceView](https://github.com/dani-gavrilov/GDPerformanceView-Swift) and head over to our `AppDelegate`. We'll add a bit of code:

```swift
GDPerformanceMonitor.sharedInstance.startMonitoring { (textLabel) in
  textLabel?.backgroundColor = .black
  textLabel?.textColor = .white
}
```

Here we're telling `GDPerofrmanceMonitor` to start its engines, then customizing the look and feel of the label that appears in the status bar.

When we Build & Run, here's what we get:

![Image 1 of 2 from bite #290: Monitoring Performance with GDPerformanceView](https://media.littlebitesofcocoa.com/290-1.png)

Neat! By default [GDPerformanceView](https://github.com/dani-gavrilov/GDPerformanceView-Swift) will show the app and device version. This is great in some cases (QA testing, beta builds), but in our case we don't really need it. Let's them both off:

```swift
GDPerformanceMonitor.sharedInstance.appVersionHidden = true
GDPerformanceMonitor.sharedInstance.deviceVersionHidden = true
```

![Image 2 of 2 from bite #290: Monitoring Performance with GDPerformanceView](https://media.littlebitesofcocoa.com/290-2.png)

Beautiful. Now we'll always know exactly how well our app is behaving, and we'll be able to identify issues as they happen.

[GDPerformanceView](https://github.com/dani-gavrilov/GDPerformanceView-Swift) has one more trick up its sleeve. 🎩

We can actually subscribe to performance updates and do whatever we'd like with the data.

Let's try this out. First we'll subscribe to updates by making our `AppDelegate` conform to the provided `GDPerformanceMonitorDelegate` protocol:

```swift
extension AppDelegate : GDPerformanceMonitorDelegate {
  func performanceMonitorDidReport(fpsValue: Float, cpuValue: Float) {
    // TODO
  }
}
```

Then, we'll set it as the delegate for the shared `GDPerformanceMonitor` in our `didFinishLaunching`:

```swift
GDPerformanceMonitor.sharedInstance.delegate = self
```

Nice. Now we need to do something interesting with these updates. Let's use the [Taptic Engine](http://www.imore.com/iphone-7s-taptic-engine) ([Bite #269](https://littlebitesofcocoa.com/269-taptic-engine-basics)) to provide some force feedback if we hit the CPU too hard:

```swift
func performanceMonitorDidReport(fpsValue: Float, cpuValue: Float) {
  if cpuValue > 50 {
    UIImpactFeedbackGenerator(style: .heavy)
      .impactOccurred()
  }
}
```

Neat! We could also toss these values into an array somewhere and use it to build charts, etc.

Learn more about [GDPerformanceView](https://github.com/dani-gavrilov/GDPerformanceView-Swift) at [git.io/gdperformance](https://git.io/gdperformance).

Topics

- [Libraries](https://littlebitesofcocoa.com/topics/7-libraries)

## [#289: Displaying Log Messages in Apps with TinyConsole 📃📲](https://littlebitesofcocoa.com/289-displaying-log-messages-in-apps-with-tinyconsole)

 Monday January 16th, 2017

Topics

- [Libraries](https://littlebitesofcocoa.com/topics/7-libraries)

**Xcode** offers a wealth of great tools for debugging. Sometimes though, we'd like to be able to debug or evaluate the inner-workings of our app without needing to be connected to **Xcode's debugger.**

Today we'll check out [TinyConsole](https://github.com/Cosmo/TinyConsole) by [Devran Ünal](https://github.com/Cosmo), a library that lets us easily display our log messages directly inside our app. Let's take a look.

We'll install [TinyConsole](https://github.com/Cosmo/TinyConsole) into our app, then slightly modify some code in our `AppDelegate` to set it up.

Instead of assigning our root view controller like this:

```swift
self.window.rootViewController = SpaceshipsViewController()
```

We'll wrap our root view controller in a `TinyConsoleController`:

```swift
self.window = TinyConsoleController(
  rootViewController: SpaceshipsViewController()
)
```

That's it. Now all we need to do is add some log messages throughout our code. We can do this with calls like:

```swift
TinyConsole.print("spacehip id: \(spaceship.id)")
```

Now, we can launch our app and try it out. When running on a device, we can simply shake the device to show/hide the console view.

(**Pro Tip:** Press **⌘⌃Z** to simulate a shake in the **iOS Simulator**).

![Image from bite #289: Displaying Log Messages in Apps with TinyConsole](https://media.littlebitesofcocoa.com/289-1.gif)

Neat! [TinyConsole](https://github.com/Cosmo/TinyConsole) doesn't stop there though, we can also use colors:

```swift
TinyConsole.print("Crew Member Saved!", color: UIColor.green)
```

and add Markers:

```swift
TinyConsole.addMarker()
```

Finally, there's a few more gestures available (in addition to shaking to hide/show).

We can **swipe** to add a Marker, **tap with 2 fingers** to log something manually, or **tap with 3 fingers** to show an Action Sheet that allows us to send our log messages as an email.

Learn more about [TinyConsole](https://github.com/Cosmo/TinyConsole) at git.io/tinyconsole

Topics

- [Libraries](https://littlebitesofcocoa.com/topics/7-libraries)

## [#285: Generating Random Data with RandomKit 🎲](https://littlebitesofcocoa.com/285-generating-random-data-with-randomkit)

 Monday November 7th, 2016

Topics

- [Libraries](https://littlebitesofcocoa.com/topics/7-libraries)

Whether we need sample values while prototyping our **app's** interface, or some multipliers for our **game's** logic, *random data* can be incredibly useful when programming. Today we'll check out a great library from [Nikolai Vazquez](https://github.com/nvzqz) called [RandomKit](https://github.com/nvzqz/RandomKit) that makes generating *random data* both simple and intuitive. Let's begin.

[RandomKit](https://github.com/nvzqz/RandomKit) is built on a set of [Swift Protocols](https://littlebitesofcocoa.com/232-practical-protocols). We're provided `Random`, `RandomWithinRange`, `RandomToValue`, and many more. [RandomKit](https://github.com/nvzqz/RandomKit) then extends a *bunch* of **types** to conform to these **protocols**.

*(This is great because it means we can easily add [RandomKit](https://github.com/nvzqz/RandomKit)-style functionality to our own **types**, if we ever need to. Neat.)*

Let's try out the basics. Some of the most common things to generate randomly are numbers and booleans. [RandomKit](https://github.com/nvzqz/RandomKit) has us well covered here, supporting all the major numerical **Foundation** types (and more):

```swift
Double.random() // 0.6472946529383645
Int.random(within: 1...10) // 7
NSNumber.random(within: -5...5)  // -3
CGFloat.random(0...1)  // 0.27969591675319
Bool.random() // false
```

Neat. Next up, Strings:

```swift
String.random(ofLength: 5) // "$-=5t"
Character.random() // "#"
```

We can also easily grab a random element from any **Swift** `Sequence` or `Collection`:

```swift
"Little Bites of Cocoa".characters.random // "o"
["Han", "Luke", "Chewie"].random // "Luke"
NSDictionary(dictionary: [ "firstName": "Han", "lastName": "Solo" ]).random // ("lastName", "Solo")
```

But wait, there's more! [RandomKit](https://github.com/nvzqz/RandomKit) is incredibly comprehensive. Let's try some more advanced functionality like `Dates`:

```swift
Date.random(within: Date.distantPast...Date())  // "Feb 7, 472, 5:40 AM"
```

URLs:

```swift
URL.random() // https://stackoverflow.com
```

...or even `UIColors` and `NSColors`:

`UIColor.random(alpha: false)`  

Last but not least, we can even grab random values for **CoreGraphics** types:

```swift
CGPoint.random(within: 0...50, 0...50) // {x 23.284 y 45.302 }
CGSize.random(within: 0...50, 0...50) // {w 29.475 h 12.863 }
CGRect.random() // {x 3.872  y 46.15  w 8.852  h 20.201}
```

These examples were just a *(sorry)* random-sampling of [RandomKit](https://github.com/nvzqz/RandomKit)'s functionality. It has a ton more to offer.

Learn more about [RandomKit](https://github.com/nvzqz/RandomKit) at [git.io/randomkit](http://git.io/randomkit)

 

Page 1 of 10

[Next   ](https://littlebitesofcocoa.com/topics/7-libraries?page=2)
