Raw Values vs Associated Values in Swift

January 20, 2019

Raw values are used to associate constant (literal) values to enum cases. The value type is part of the enum type, and each enum case must specify a unique raw value (duplicate values are not allowed).

The following example shows an enum with raw values of type Int:

enum IntegerEnum : Int {
    case one = 1
    case two = 2
    case three = 3

An enum value can be converted to its raw value by using the rawValue property:

var intEnum: IntegerEnum? = IntegerEnum(rawValue: 1)

Associated values are used to associate arbitrary data to a specific enum case. Each enum case can have zero or more associated values, declared as a tuple in the case definition:

enum AssociatedEnum {
    case empty
    case in(value: Int)
    case tuple(value: Int, text: String, data: [Float])

Whereas the type(s) associated to a case are part of the enum declaration, the associated value(s) are instance specific, meaning that an enum case can have different associated values for different enum instances.