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

5
我正在寻找一种方法来打印Swift中枚举的相关值。例如,下面的代码应该为我打印出“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,无法理解这个错误信息的含义。有人知道是否可能吗?


case let (a, b) 相当于 case (let a, let b) - rkb
1个回答

2
问题在于您给您的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
    }
}

现在它不会报错,但是在使用在线编译器runswiftlang.com时仍会打印出 (Enum Value) - rkb
并非所有环境都能识别“Printable”协议的一致性。如果您仍然遇到此问题,请直接使用description属性,直到环境升级到Swift 1.2(我想):println(productCode.description) - Nate Cook

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接