SLN SLN - 6 months ago 14
Swift Question

Raw Value of Enumeration, Default value of a class/structure, What's the different?

In Swift, there is Raw Value in Enumeration and Default Value in class and structure. What's the different? Can someone explain that for me?

Ex. of Raw Values of Enumeration (From the Office Swift Document)

enum ASCIIControlCaracter: Character {
case Tab = "\t"
case LineFeed = "\n"
case CarriageReturn = "\r"
}

Answer

From Apple docs:

Raw Values

The barcode example in Associated Values shows how cases of an enumeration can declare that they store associated values of different types. As an alternative to associated values, enumeration cases can come prepopulated with default values (called raw values), which are all of the same type.

So I guess it is the same.

On the other hand, with "default value", you may be referring to the default value of an enum case where no values have been set, for example:

enum TestEnum: Int  {    
    case A
    case B    
}

Here, TestEnum.A has a default value of 0, and TestEnum.B has a default value of 1.

Raw value refers to the actual value of an enum case (in the enum's type, in this example it would be Int):

enum TestEnum: Int  {    
    case A
    case B = 3   
}

Here, TestEnum.A has the default value (which is also the raw value) of 0, and TestEnum.B has a raw value of 3 (which is no longer the default value).

Comments