簡體   English   中英

如何在Swift枚舉中打印關聯值?

[英]How to print associated values in Swift enumerations?

我正在尋找一種在Swift中打印enumetations的相關值的方法。 即。 以下代碼應該為我打印"ABCDEFG" ,但事實並非如此。

enum Barcode {
    case UPCA(Int, Int, Int, Int)
    case QRCode(String)
}

var productCode = Barcode.QRCode("ABCDEFG")
println(productCode)

// prints (Enum Value)

閱讀 stackoverflow問題的答案,這與打印枚舉的原始值有關,我嘗試了下面的代碼,但它給了我一個錯誤

enum Barcode: String, Printable {
    case UPCA(Int, Int, Int, Int)
    case QRCode(String)
    var description: String {
        switch self {
            case let UPCA(int1, int2, int3, int4):
                return "(\(int1), \(int2), \(int3), \(int4))"
            case let QRCode(string):
                return string
        }
    }
}

var productCode = Barcode.QRCode("ABCDEFG")
println(productCode)

// prints error: enum cases require explicit raw values when the raw type is not integer literal convertible
//        case UPCA(Int, Int, Int, Int)
//             ^

由於我是Swift的新手,我無法理解錯誤消息是什么。 有人知道是否可能。

問題是您在Barcode枚舉String添加了顯式原始類型。 聲明它符合Printable是您所需要的:

enum Barcode: Printable {
    case UPCA(Int, Int, Int, Int)
    case QRCode(String)
    var description: String {
        // ...
    }
}

編譯器的抱怨是您沒有使用非整數原始值類型指定原始值,但無論如何都不能使用關聯值。 沒有關聯類型的原始字符串值可能如下所示:

enum CheckerColor: String, Printable {
    case Red = "Red"
    case Black = "Black"
    var description: String {
        return rawValue
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM