【问题标题】:Is it possible to get enum description from variable when enum conforms protocol CustomStringConvertible?当枚举符合协议 CustomStringConvertible 时,是否可以从变量中获取枚举描述?
【发布时间】:2017-07-26 08:44:15
【问题描述】:

当枚举符合协议CustomStringConvertible时,是否可以从变量中获取枚举描述?简化定义为:

enum myEnum: CustomStringConvertible {

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

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

没有协议很容易:

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"

但是通过协议我只能得到前两个案例

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

因此,case .aaa1, .aaa2 没有孩子,所以我无法将这些 case 彼此分开(当然 switch-case 除外)。在当前情况下,我可以扩展该枚举的功能,但无法编辑之前所做的。

有没有办法获得这种情况的一般字符串描述?

【问题讨论】:

    标签: swift reflection enums swift3


    【解决方案1】:

    是的,您可以使用 Swift 的镜像反射 API。实例的枚举案例被列为镜像的子项,您可以像这样打印它的标签和值:

    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
        }
    }
    

    【讨论】:

    • 也许上面不清楚,但要求是:1.描述是遗留属性,不可能改变它的逻辑2.我需要得到类似于调试器描述的“字符串描述”。例如:“en.aaa1”“en.aaa2”“en.two((2.0, 3.0))”等当然不用为每种情况使用 switch :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多