Introducing `IdentifiedEnumCases` Swift Macro

When a Swift enumeration has associated values, its cases can't be referenced as code. It would be so nice to reference the names of cases, even when an associated value isn't known.

This macro creates an ID enum, to refer to each case. In addition, it also creates a computed variable id so that the identifier of each case is easily available.

In my past projects, I've typed this up by manually each time. But now with Swift Macros, it's easy! The Swift enumeration just needs an annotation, and identifiers for each case will be created!

Example

Suppose we use a large enum to specify navigation in our app. (And the code is shared with our Swift backend for beautiful universal links!) When we want to convert our AppRoute to an URL, or convert an URL back to an AppRoute, it's very useful to reference the ID of the case, without the associated value.

import IdentifiedEnumCases

@IdentifiedEnumCases
public enum AppRoute {
  case item(ItemRoute)
  case user(UserRoute)
}

generates to

public enum AppRoute {
  case item(ItemRoute)
  case user(UserRoute)

  public var id: ID {
    switch self {
    case .item: .item
    case .user: .user
  }

  public enum ID: String, Hashable, CaseIterable {
    case item
    case user
  }
}

GitHub Link

GitHub Actions does not yet run Swift 5.9, so the tests are failing.

6 Likes