Can associated values and raw values coexist in Swift enumeration?

后端 未结 5 1792
遇见更好的自我
遇见更好的自我 2020-12-04 19:22

There are examples on Swift book demonstrating associated values and raw values separately, is there a way to define enums with the two features together?

I have tri

5条回答
  •  余生分开走
    2020-12-04 19:39

    I solved it like this:

    enum Barcode {
    
       case UPCA(Int, Int, Int)// = "Order 1"
       case QRCode(String)// = "Order 2"
    
       static func customRawValue(rawValue: String) -> Barcode? {
    
           switch rawValue {
    
           case "Order 1": return Barcode.UPCA(0, 0, 0)
           case "Order 2": return Barcode.QRCode("")
           default: return nil
           }
        }
    
        var customRawValue : String {
    
           switch self {
           case .UPCA: return "Order 1"
           case .QRCode: return "Order 2"
           }
        }
    }
    
    if let barcode = Barcode.customRawValue("Order 1") {
    
       print("Barcode found with custom rawValue: \(barcode)")
    
       print("Custom rawValue: \(barcode.customRawValue)")
    }
    

    It's somewhat hacky, but this solution worked great for my purpose!

提交回复
热议问题