2017-10-11 26 views
2

我有以下枚舉如何從此枚舉中獲取CustomStringConvertible說明?

enum Properties: CustomStringConvertible { 
    case binaryOperation(BinaryOperationProperties), 
    brackets(BracketsProperties), 
    chemicalElement(ChemicalElementProperties), 
    differential(DifferentialProperties), 
    function(FunctionProperties), 
    number(NumberProperties), 
    particle(ParticleProperties), 
    relation(RelationProperties), 
    stateSymbol(StateSymbolProperties), 
    symbol(SymbolProperties) 
} 

和結構都這個樣子

struct BinaryOperationProperties: Decodable, CustomStringConvertible { 
    let operation: String 
    var description: String { return operation } 
} 

那麼,如何讓該枚舉符合CustomStringConvertible?我嘗試了一個簡單的getter,但很明顯,它調用自己,我想調用特定的結構的代替。

獎勵積分:是不是有一個名稱定義的枚舉?

回答

2

這樣的枚舉被稱爲枚舉與相關值

我想通過在案件手動切換實現description

extension Properties: CustomStringConvertible { 
    var description: String { 
     switch self { 
     case .binaryOperation(let props): 
      return "binaryOperation(\(props))" 
     case .brackets(let props): 
      return "brackets(\(props))" 
     ... 
     } 
    } 
} 

編輯:另一種方法是使用雨燕的Mirror反射API。實例的枚舉情況下,被列爲鏡的孩子,你可以打印的標籤和值是這樣的:

extension Properties: CustomStringConvertible { 
    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 
    } 
} 

(這是一個通用的解決方案,應該是多種類型,而不僅僅是枚舉使用。你可能不得不添加一些換行符爲具有比一個孩子更多類型)


編輯2:Mirror也是什麼printString(describing:)使用的類型不符合Custom[Debug]StringConvertibleYou can check out the source code here

+0

我結束了使用第一個選項,因爲輸出對於我所需要的更加緊湊,但是感謝您徹底! – Morpheu5