Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get enum description from variable when enum conforms protocol CustomStringConvertible?

Is it possible to get enum description from variable when enum conforms protocol CustomStringConvertible? Simplified definition is:

enum myEnum: CustomStringConvertible {

  case one(p1: Int)
  case two(p: CGPoint)
  case aaa1
  case aaa2

  var description: String {
    return "useless text"
  }
}

Without protocol it's easy:

let testCases = [en.one(p1: 10), en.two(p: CGPoint(x: 2, y: 3)), en.aaa1, en.aaa2]
testCases.forEach{ 
  print( String(reflecting: $0 ), terminator: "\t\t" ) 
} 
=> "en.one(10)      en.two((2.0, 3.0))      en.aaa1     en.aaa2"

But with protocol I'm able only to get first two cases

testCases.forEach{ 
   Mirror(reflecting: $0).children.forEach{ label, value in
      print( label == nil ? value : (label!, value))
   } 
} 
=> ("one", 10), ("two", (2.0, 3.0))

Thus, cases .aaa1, .aaa2 don't have children so I can't separate those cases from each other (except switch-case of course). Within current situation I can extend functionality of that enum but can't edit what was done before.

Is there a way to get general string description for such case?

like image 889
Ilya Levchenko Avatar asked Apr 24 '26 13:04

Ilya Levchenko


1 Answers

Yes, you can use Swift's Mirror reflection API. The enum case of an instance is listed as the mirror's child and you can print its label and value like this:

extension myEnum {
    var description: String {
        let mirror = Mirror(reflecting: self)
        var result = ""
        for child in mirror.children {
            if let label = child.label {
                result += "\(label): \(child.value)"
            } else {
                result += "\(child.value)"
            }
        }
        return result
    }
}
like image 58
Leonardo Durazo Avatar answered Apr 27 '26 01:04

Leonardo Durazo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!