Topics

#249: Enums in Swift 3 🐤

Topics

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.

Before:

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

After:

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.