lundi 6 mars 2017

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?





Aucun commentaire:

Enregistrer un commentaire