Topics

#209: Swift Enums Cookbook 🍳📖

Topics

Swift Enums are super handy. With associated values, they can be used in some quite interesting ways. Today we'll check out a couple. These aren't working examples, but might spark some ideas. Let's take a look.

Enums with Extensions

Keeping colors in one place is a great way to ensure consistency in a project.

public enum Color : String {
  case Green = "28A860"
  case Blue = "3B87D6"
}

extension Color : UIColorConvertible {
  public func asColor() -> UIColor {
    return UIColor(hexString: rawValue)
  }
}

This same technique is great for images too!

Enums with Closures

This one is a little crazy (but fun!). Imagine we had our own custom system for laying out views in our app. We could not only describe that system perfectly with enums, we could even add a little more dynamic spice to the mix by making one of the associated values of our enum a closure. Neat!

public enum LayoutStrategy {
  case SizeToFit
  case Fixed(width: CGFloat, height: CGFloat)
  case Relative(closure: ((parentSize: CGSize) -> CGSize))
}

Enums can describe so many types of state and data. Know of a cool use of them? Send it to hello@littlebitesofcocoa.com and it might be featured here!