5

I'm looking for a way to print associated values of enumetations in Swift. ie. following code should print "ABCDEFG" for me but it doesn't.

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

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. Can someone know if it is possible or not.

Community
  • 1
  • 1
rkb
  • 514
  • 2
  • 9
  • 19

1 Answers1

2

The problem is that you added an explicit raw type to your Barcode enum—String. Declaring that it conforms to Printable is all you need:

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
    }
}
Nate Cook
  • 92,417
  • 32
  • 217
  • 178
  • Now it doesn't give an error but still prints `(Enum Value)` while using online compiler [runswiftlang.com](http://www.runswiftlang.com/) – rkb Apr 08 '15 at 05:27
  • Not all environments will recognize `Printable` protocol conformance. If you're still getting that, use the `description` property directly until the environment is upgraded to Swift 1.2 (I think): `println(productCode.description)` – Nate Cook Apr 08 '15 at 08:19