Active Filters: Swift


#302: Lazy Properties πŸ€πŸ’€


Today we're going to begin looking at the lazy keyword in Swift. It describes some functionality in the language for what Apple calls " just-in-time calculation" of work.

This is great for times when we have expensive work to perform, or maybe the work is just some ugly complex code we'd like to tuck away. Perhaps we simply want to better compartmentalize the bits of our code that initialize UI elements, the use cases are plenty.

Today we'll start with Lazy Variables. Let's dive in!

Say we have a View Controller with a titleLabel. Pretty old school standard stuff.

We need to create the titleLabel, save it to a property, configure some stuff about it, then add it into the view heirarchy.

We want this work to be done after the view is loaded, and not when the view controller is first created, so we are forced to put it in viewDidLoad.

Additionally, we're forced to use a UILabel! force-unwrapped type on our titleLabel property to make the compiler happy.

It ends up looking something like this:

class ViewController: UIViewController {
  var titleLabel : UILabel!

  override func viewDidLoad() {

    titleLabel = UILabel()

    titleLabel.font = UIFont(name: "Source Sans Pro", size: 18.0)
    titleLabel.textColor = UIColor.brown


Let's make our titleLabel lazy and clean this junk up:

class ViewController: UIViewController {
  lazy var titleLabel : UILabel = {
    let label = UILabel()

    label.font = UIFont(name: "Source Sans Pro", size: 18.0)
    label.textColor = UIColor.brown

    return label

  override func viewDidLoad() {



We've now dramatically improved our viewDidLoad implementation. Cool.

We've also neatly compartmentalized the bit of code that sets up that label. Cool cool.

Perhaps most importantly though, we've now better expressed our intentions using language keywords (and their resulting behaviors), Cool cool cool.

Note: We have to use var instead of let when defining lazy properties like this. Our property might not (likely won't) have an initial value until after the instance of our view controller is created and its view is loaded. This completely breaks the rules of lets (constants).

That's all for now, in future Bites we'll look at other lazy behaviors in Swift!


#257: Property Observers on Local Variables 🐀


We first looked at Swift's property observers back in Bite #179. They're a great way to know when a property's value is about to change, or just finished changing.

Traditionally, they look like this:

class Spaceship : NSObject {
  var name: String {
    didSet { print(name) }

Nothing too fancy here, just printing the latest value for name, anytime a ship's name changes.

This works great for properties on types, but it turns out we can actually use these same observers on local variables as well:

var name = "Tim Cook" {
  didSet { print(name) }

name = "Eddy Cue"
name = "Craig Federighi"

This prints:

Eddy Cue
Craig Federighi


Kelan Champagne mentions an interesting technique for super-simple value-change tracking:

var previousStatuses = [String]()
var awayMessage: String? = nil {
  willSet {
    guard let awayMessage = awayMessage else { return }

awayMessage = "out to lunch, brb"
awayMessage = "eating dinner"
awayMessage = "emo song lyrics"
awayMessage = nil

print("Previous: ", previousStatuses)

This prints:

Previous: ["out to lunch, brb", "eating dinner", "emo song lyrics"]

This technique might not make sense in many situations, but is a nice feature to know about in case we can ever benefit from it.

A huge thanks to both Kelan Champagne and Chris Eidhof for pointing this out!

Swift Protocols are great. They allow us to express the idea of expecting a set of functionality, without needing to expect a specific concrete type. Today we'll look at creating a Protocol to make working with colors in our apps a bit more flexible. Let's dive in. 🏊

We'll start by creating a new Protocol, giving it a conventional name, and require just one read-only property from our conforming types. This property will always return a UIColor.

public protocol ColorConvertible {
  var colorValue: UIColor { get }

Now, let's try this new Protocol out by creating an enum that represents the different colors we use in our app:

public enum SpaceshipsColors : String {
  case white = "FFFFFF"
  case red = "E2574C"
  case gold = "EFC75E"
  case darkTeal = "314D5B"
  case lightTeal = "3CB39E"
  case spaceGray = "233640"
  case aluminum = "6A838D"
  case black = "000000"

Looking pretty good, now let's extend our enum to conform to ColorConvertible.

We're using Hue here (Bite #195) to convert our hex color code Strings into UIColors.

extension SpaceshipsColors : ColorConvertible {
  public var colorValue: UIColor {
    return UIColor.hex(rawValue)

Now we can reference colors in our code by name, and get full autocompletion when typing them. Using our new Protocol is super simple, let's make a quick UIView subclass to show it off:

class SpaceshipNameHeaderView : UIView {
  var nameLabel: UILabel
  var nameTextColor: ColorConvertible? {
    didSet {
      nameLabel.textColor = nameTextColor?.colorValue

It'd be nice if we could still supply "one-off" UIColors as well. No problem, let's simply conform UIColor itself to be ColorConvertible. We can just return self:

extension UIColor : ColorConvertible {
  public var colorValue: UIColor {
    return self

Finally, we can use it like this:

let hv = SpaceshipNameHeaderView()

// works!
hv.nameTextColor =

// works just as well!
hv.nameTextColor = SpaceshipsColors.aluminum

Swift Protocols can help us write code that is both expressive and quite flexible. They can take a while to get a handle on, but understanding them is a key step towards unlocking the full power of Swift.

Today we'll take our first step towards contributing to the Swift language. We'll learn how to download the codebase, compile it, and run tests. Let's get started!

First, we'll prepare our environment. We'll be doing all of this on a Mac today, but all of this is also possible on Linux (and a bunch of other platforms).

We'll begin by using homebrew to install a couple of build tools:

brew install cmake ninja

Once that's done, we'll make a new directory somewhere sensible where we can put everything:

mkdir -p ~/projects/swift

Next, we'll do the first clone:

git clone

Once this is done, we'll pull down all the dependencies and other projects involved with building Swift:

./swift/utils/update-checkout --clone-with-ssh

We have now cloned and checked out a lot of code, it's time to get building. We'll head into the swift directory and kick off a standard build, then run basic tests like this:

cd swift
./utils/build-script -r -t

That's it! At this point we can go get a cup of coffee (no really, this is going to take a while, even on a fast machine).

With these skills in hand though, we can now edit code, and see what effects our changes have on tests.

We can run basic tests at anytime with:

./utils/build-script --test

Or run more intensive validation tests like this:

./utils/build-script --validation-test

This is just the beginning, in the future we'll look at fixing a Swift bug, and contributing our work back to the project.


#250: Improvements to C APIs in Swift 3 🐀


We’ve covered a little about working with C APIs in Swift back in Bite #189. Swift 3 brings us a ton of new goodies and improvements around C APIs, let's dive right in and take a look.

Swift 3 improves upon a number of areas of C API usage in Swift, but the biggest one is importing functions as members. Essentially, taking free floating C functions, renaming them, and shoving them onto a type as functions.

One place where this behavior really shines is when using CoreGraphics to draw into a view.

Here's some basic drawing code in Swift 2:

guard let context: CGContext = UIGraphicsGetCurrentContext() else { return }

CGContextSetStrokeColorWithColor(context, UIColor.redColor().CGColor)
CGContextSetLineWidth(context, 2)
CGContextDrawPath(context, .Stroke)

In Swift 3, the code to do the same would be:

guard let context: CGContext = UIGraphicsGetCurrentContext() else { return }

context.strokeColor =
context.lineWidth = 2
context.drawPath(mode: .Stroke)

The mechanisms powering this conversion under the hood are pretty neat. The full (now implemented) proposal can be found here, but here's a quick overview:

The first is a bit of automatic inference. Many APIs (like CoreGraphics and CoreFoundation) use consistent (albeit often verbose) naming schemes for their functions. The Swift compiler can now exploit this to (for example) detect functions returning a specific type and convert them into init functions in Swift.

So this C function would come in to Swift 2 like this:

func CGColorCreate(space: CGColorSpace?, _ components: UnsafePointer<CGFloat>) -> CGColor?

But in Swift 3 it's an init function:

extension CGColor {
  init?(space: CGColorSpace?, components: UnsafePointer<CGFloat>)

There's tons more of these automatic inferences for things like detecting getter/setter pairs of functions, converting Boolean functions into Bool properties, etc.

Finally, authors of C libraries can customize exactly how their functions are imported into Swift using the new swift_name macro.

Here's an example from the proposal that demonstrates how we can define which type our function gets imported on to.

struct Point3D rotatePoint3D(Point3D point, float radians)

The string parameter we pass to swift_name has a bunch of little extra syntax to import things as inits, regular functions, getters/setters, etc.

As always when talking about Swift improvements, it's a good idea to check out the full proposal for more info.


#249: Enums in Swift 3 🐀


We've been looking at some the changes coming in Swift 3 recently in Bites #243 and #244. We'll continue our tour today by checking out what is new the world of Swift Enums. Let's dive right in.

We'll start with the obvious, in Swift 2 (and earlier) enums have been PascalCased. In Swift 3, they are camelCase.


enum PersonalityTrait {
  case Extraversion(multiplier: Float)
  case Agreeableness(multiplier: Float)


enum PersonalityTrait {
  case extraversion(multiplier: Float)
  case agreeableness(multiplier: Float)

The Swift 3 migrator in Xcode 8 will prompt us to convert all of our enums to this new convention.

Additionally, all of Apple's frameworks have this new convention applied:

label.textAlignment = .right
label.baselineAdjustment = .alignCenters
label.lineBreakMode = .byWordWrapping

In Swift 2, there was some inconsistency about the requirements around when the "dot" in the "dot notation" was required.

In Swift 2, all of this was valid:

enum AdvertisementKind {
  case Small, Medium, Large, Giant

  func debugDescription() -> String {
    switch self {
      case Small: return "Small Ad"
      case .Medium: return "Medium Ad" // leading dot

    if self == Large {
      return "Large Ad"

    if self == .Giant {
      return "Giant Ad"

Note how enum cases are used interchangeable both with and without dots.

In Swift 3, this has been cleaned up and dots are now required when using this shorthand style to access enum cases. There's one exception and that is static functions on enums, which still infer self:

enum AdvertisementKind {
  case small, medium, large, giant

  static func randomKind() -> AdvertisementKind {
    return medium

Watching Swift evolve in these ways is a great way to understand not just the syntactic structural changes being made, but also the reasoning and goals behind them. Those interested should definitely read over the proposal that prompted this change here.

The Swift language is always evolving. Bugs are being fixed, new proposals are implemented, etc. It'd be great if we could try out these features out as they're being implemented, without having to wait for official releases.

Today we'll take a look at how to download, install, and try out the latest Swift Toolchain in Xcode. Let's get started!

We'll begin by heading to and looking for the "Snapshots" section. Here we can also find many other preview releases, etc.

Click "Xcode" to download an installer:

We'll run open the installer, and complete its steps.

We can now open Xcode and select our new Toolchain.

We can also manage Toolchains in Xcode's preferences:

With our new Toolchain selected, all builds will use it, neat!

Getting involved with Swift's development is a great way to stay informed on where things are headed. We'll look at getting even more involved in future Bites!

We've covered GCD a few times back in Bites #85 & #35. This year, GCD is getting a huge overhaul that brings it into the modern world of Swift. Today we'll take a look at what's changed, let's dive in.

TLDR: Grand Central Dispatch now has a richly typed Swift 3 API.

Here's a basic usage example:

let queue = DispatchQueue(label: "com.jakemarsh.image-processing")

queue.async {
  let thumbnail = image.resize(to: thumbnailSize(for: image))

  DispatchQueue.main.async { imageView.image = thumbnail }

Here we create a new queue, and enqueue some image processing work on it. Then, we do the same thing, but back on the main queue, enqueueing the work of setting resized image on our imageView there.

That's just the beginning. Here's a few more examples of how to use the new "swifty" GCD:

Time & Delay:

let delayTime = + .seconds(1)

DispatchQueue.main.after(when: delayTime) {

For seasoned GCD users, it may take some getting used to, but the new API is much safer and more intuitive to use in Swift. Neat!


#243: The Great Swift 3 Rename 🐀


We've been able to watch Swift 3 materialize through the Swift Evolution mailing list throughout the year, and with WWDC 2016 behind us, we have a pretty clear picture of what Swift 3 will be.

Today we'll start taking a look at what's new and changed in this release, and how it can help us build our apps. First up is the "Great Rename", Let's begin.

It all started with this proposal on Swift Evolution:
"Better Translation of Objective-C APIs into Swift".

When Swift was first announced, one of the huge selling points was how we could use the same Cocoa APIs we were already familiar with.

Unfortunately, this meant a lot of Objective-C baggage found its way into the Swift code we were writing.

Swift 3 aims to fix this by improving the way Swift imports Objective-C code.

Take this Swift 2 code:


The function is imported with a definition like this:

func addLineToPoint(_: CGPoint)

In Swift 3, this would instead be imported as:

func addLine(to point: CGPoint)

And we could use it like this:

path.addLine(to: containerTop)

Swift 3 removes the repetitive names of the types, and properly brings in a (now required) argument label for the first parameter.

Additionally, Swift 3 drops the NS prefix from Foundation types, so instead of:

var now = NSDate()

We'll now be writing:

var now = Date()

Many Foundation types also now get proper Swift let/var mutability semantics:

var now = Date()
now.addTimeInterval(60) // works

let now = Date()
now.addTimeInterval(60) // compiler error

Swift 3 also prepends the word β€˜is' to imported Objective-C Boolean properties, and converts enums to be lowercased:

path.isEmpty // was just path.empty in Swift 2
var formatter = NumberFormatter()
formatter.numberStyle = .spellOut

That's all for now, next time we'll continue looking at more Swift 3 changes and enhancements.

Swift Protocols are awesome. Understanding how they can (or should) fit into our code can be tricky. Today we'll take a baby step into the world of protocols with a simple, but "real" example and try to illustrate the upsides. Let's get started.

We're going to be fancy and abstract away some of our layout code. So we'll create a little struct to hold some layout settings like this:

struct LayoutSettings {
  let direction: FlexDirection
  let justification: Justification
  let alignmentSelf: Alignment
  let alignmentChildren: Alignment

  /// ...etc

See? Fancy. This is great if we want to specify each individual combination each time, but it'd be nice if we could define some sort of "pre-canned" layouts that we could use by name. Sounds like a great job for a Swift Enum.

enum CannedLayout {
  case FillParent
  case SizeToFit
  case Absolute(point: CGPoint)
  case Relative(closure: (parentFrame: CGRect) -> CGSize)

Lovely, this will be handy. How are we going to wire all this together though? Simple, we'll make a Protocol that's only responsibility is to convert itself to a LayoutSettings.

protocol LayoutSettingsConvertible {
  func layoutSettings() -> LayoutSettings

LayoutSettings can adopt this extremely simply:

extension LayoutSettings : LayoutSettingsConvertible {
  func layoutSettings() -> LayoutSettings { return self }

Whew! That was tough.

Making our CannedLayout Enum adopt our new Protocol is a bit more involved, but really just means switch-ing over self and return the proper combination of settings for each case.

extension CannedLayout : LayoutSettingsConvertible {
  func layoutSettings() -> LayoutSettings {
    switch self {
      case .FillParent: return LayoutSettings(direction: .Vertical, justification: .Start, alignmentSelf: .Stretch, alignmentChildren: .Start)
      /// ...etc

All that's left is to use this new protocol somewhere. Let's wire this up to UIView to make it useful:

extension UIView {
  func layout(settings: LayoutSettingsConvertible) {
    /// configure the view for the new settings here

Neat! Now, we can use configure views with one of our canned layouts:

let v = UIView(frame: .zero)

But we can also easily configure them the "long way" using a full LayoutSettings object directly:

let v = UIView(frame: .zero)
v.layout(LayoutSettings(direction: .Vertical, justification: .Start, alignmentSelf: .Stretch, alignmentChildren: .Start))

Now that we have this simple protocol, we can make other helper types like this:

struct Row : LayoutSettingsConvertible {
  func layoutSettings() -> LayoutSettings {
    return LayoutSettings(direction: .Horizontal, justification: .Start, alignmentSelf: .Stretch, alignmentChildren: .Start)

That's just the basics when it comes to Protocols. They have much more to offer. More on this topic soon!

Page 1 of 4