简体   繁体   English

如何在Swift枚举中打印关联值?

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

I'm looking for a way to print associated values of enumetations in Swift. 我正在寻找一种在Swift中打印enumetations的相关值的方法。 ie. 即。 following code should print "ABCDEFG" for me but it doesn't. 以下代码应该为我打印"ABCDEFG" ,但事实并非如此。

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

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

// prints (Enum Value)

Reading the answers to this stackoverflow question, which is related to printing raw values of enumerations, I tried following code but it gives me an error 阅读 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)
//             ^

Since I'm new to Swift I can't understand what error message is about. 由于我是Swift的新手,我无法理解错误消息是什么。 Can someone know if it is possible or not. 有人知道是否可能。

The problem is that you added an explicit raw type to your Barcode enum— String . 问题是您在Barcode枚举String添加了显式原始类型。 Declaring that it conforms to Printable is all you need: 声明它符合Printable是您所需要的:

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

The compiler's complaint is that you didn't specify raw values with your non-integer raw value type, but you can't do that with associated values anyway. 编译器的抱怨是您没有使用非整数原始值类型指定原始值,但无论如何都不能使用关联值。 Raw string values, without associated types, could look like this: 没有关联类型的原始字符串值可能如下所示:

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