What's the difference between these two enums in swift?

enum MyEnum {
    case A, B, C
}

enum MyEnum2 {
    case A
    case B
    case C
}

      

What's the difference between these two enum enums?

+3


source to share


2 answers


There is no difference between the two syntaxes - it is your personal preference to use one and the other.

Swift allows you to add separate case

to one enum

so you can group constants enum

with similar related values, e.g. as an example book Barcode

:



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

      

In situations where you are defining "plain" enum

with no associated values, either of these two syntaxes would be good choices.

+1


source


I think it's probably worth mentioning that if you don't define the type and initialize the first element, the enums won't have any raw values.

enum MyEnum {
    case A, B, C
}

let myEnum = MyEnum.A
let myEnumRawValue = myEnum.rawValue 

      

will fail "MyEnum" does not have a member named "rawValue".

enum MyEnum:Int {
    case A = 0, B, C
}

let myEnum = MyEnum.A
let myEnumRawValue = myEnum.rawValue 

      

will not work.

If you don't want to declare a type or initialize enums, but still get a number (possibly indexed from some base), you can also write:



enum MyEnum {
    case A, B, C

    func enumIndex(base:Int) -> Int {
        switch self {
        case .A:
            return base
        case .B:
            return base+1
        case .C:
            return base+2
        default:
            return base
        }
    }
}

      

In this case

let myEnum = MyEnum.A
let myEnumIndex = myEnum.enumIndex(10)
println("myEnumIndex = \(myEnumIndex)")

      

will print:

myEnumIndex = 10

+1


source







All Articles