3

Why I can't define enumeration with raw values like this?

enum Edges : (Double, Double) {
    case TopLeft = (0.0, 0.0)
    case TopRight = (1.0, 0.0)
    case BottomLeft = (0.0, 1.0)
    case BottomRight = (1.0, 1.0)
}
Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

4

Because:

Raw values can be strings, characters, or any of the integer or floating-point number types.

But there is an alternative solution for you:

enum Edges {
    case TopLeft
    case TopRight
    case BottomLeft
    case BottomRight

    func getTuple() -> (Double, Double) {
        switch self {
        case .TopLeft:
            return (0.0, 0.0)
        case .TopRight:
            return (1.0, 0.0)
        case .BottomLeft:
            return (0.0, 1.0)
        case .BottomRight:
            return (1.0, 1.0)
        }
    }
}

let a = Edges.BottomLeft
a.getTuple() // returning (0, 1)
luk2302
  • 55,258
  • 23
  • 97
  • 137
  • Thank you this code works. But can you explain a bit about **Each raw value must be unique within its enumeration declaration.** –  May 27 '16 at 17:28
  • @Alexander that means you must not create two different enum entries with the same raw value, e.g `case TopLeft = 1, case TopRight = 1, case BottomLeft = 3, case BottomRight = 4` is not allowed because of the doubled `1`. – luk2302 May 27 '16 at 17:29
  • but my data is same as yours so does it means that I have to declare cases before? –  May 27 '16 at 17:32
  • @Alexander no no no, everything is fine the way it is in my answer. I included it only for completion sake. Sorry for confusing you a little bit. It only means that *if* you have custom rawValues defined for some enum then you must not use the same raw value twice inside that enum. In your case we do not even use rawValues and therefore are on the safe side already. – luk2302 May 27 '16 at 17:34
4

A tuple cannot be a raw value type of enum. From The Swift Programming Language:

Raw values can be strings, characters, or any of the integer or floating-point number types.

You could create a custom getter though:

enum Edges {
    case TopLeft, TopRight, BottomLeft, BottomRight

    var rawValue: (Double, Double) {
        switch self {
            case .TopLeft: return (0, 0)
            case .TopRight: return (1, 0)
            case .BottomLeft: return (0, 1)
            case .BottomRight: return (1, 1)
        }
    }
}
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005