Reputation: 30458
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
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