Pitch: Auto-synthesize cases for enums

I think there is a better use case that this would solve.

Eg NSAttributedString.Key:

Currently to create attributes we have to do this:

let regularAttributes: [NSAttributedString.Key: Any] = [.font: UIFont.bodyFont, .foregroundColor: UIColor.red]
let font = regularAttributes[.font]

The problem here is the the value type is any, the most obvious annoyance is that you don't get any help from the IDE autocomplete and you have to have the UIFont and UIColor types there.

It would be much better if we could write something like:

let regularAttributes: Set<NSAttributedString.Key> = [.font(.bodyFont), .foregroundColor(.red)]

Currently you can't really write a wrapper around it to do this because then you can't access the values. Ie this isn't possible:

let font = regularAttributes[.font]

or even this:

let font = regularAttributes.first { $0 == .font }
1 Like

Totally support this idea. Making Discriminant of enum with associated value public will be very helpful.

May be we should make a marker protocol, which will make Discriminant public:

public protocol DiscriminantProvideable {
  associatedtype Discriminant: CaseIterable
  var discriminant: Discriminant { get }
}

We can make it manually or generate using Sourcery. But it is inconvenient.

Here are some situations when we use it:

  1. Deeplink parsing. Every deep link in project must have ability to be encodable / decodable. CaseIterable discriminant reduce a lot of complexity in parsing.
  2. Screen states made as enums. We cover state machines with test.
public enum LoadingState<D, E: Error> {
  case isLoading
  case dataLoaded(D)
  case loadingError(E)
}

enum LoadingStateDiscriminant: CaseIterable {
  case isLoading
  case dataLoaded
  case loadingError
}

var mockStates: [LoadingState<Data, Error>] = LoadingStateDiscriminant.allCases.map {
  switch $0 {
  case .isLoading: return .isLoading
  case .dataLoaded: return .dataLoaded(Data())
  case .loadingError: return .loadingError(SomeError())
  }
}

If new state is added, then compiler helps us to add in tests.

Keep in mind, that in a big project we have over hundred of screens, and making Discriminant manually is not pleasant task.

2 Likes