Mark A. Donohoe
Mark A. Donohoe

Reputation: 30458

If an enum's case has an associated type, is it possible to get the case name without the associated data?

Given this code...

enum Label {
    case barcode(String)
    case qrRCode(String)
}

let label:Label = .barcode("barcode data")

print("The label's type is '\(label)'")

It prints

The label's type is 'barcode("barcode data")'

I'm trying to figure out how to print only

The label's type is 'barcode'

Is there a way to do that outside of writing a computed property with hardcoded strings to match the case types or manually trimming up to the opening paren?

Upvotes: 0

Views: 59

Answers (1)

user652038
user652038

Reputation:

Yes. The string you're looking for is represented by the label of the only mirror child of an enumeration case with an associated value.

protocol CaseNameWithoutAssociatedValueStringConvertible: CustomStringConvertible { }

extension CaseNameWithoutAssociatedValueStringConvertible {
  var description: String {
    Mirror(reflecting: self).children.first!.label!
  }
}
extension Label: CaseNameWithoutAssociatedValueStringConvertible { }

"\( Label.barcode("🏋️‍♂️") )" // "barcode"
"\( Label.qrRCode("🏴‍☠️") )" // "qrRCode"

Upvotes: 2

Related Questions