Sobes.tech
Junior

What are enum, raw value, and associated value in Swift?

sobes.tech AI

Answer from AI

Enum (enumeration) is a type that defines a group of related values. Raw value is a predefined value (for example, Int, String, Double) that can be associated with each enum element. Associated value is a value that can be added to a specific enum element to store additional information, not part of the raw value type.

enum HTTPStatus: Int { // raw value Int
    case success = 200
    case notFound = 404
    case internalServerError = 500
    case custom(code: Int, message: String) // associated value
}

let successStatus = HTTPStatus.success
print(successStatus.rawValue) // 200

let customStatus = HTTPStatus.custom(code: 418, message: "I'm a teapot")

switch customStatus {
case .custom(let code, let message):
    print("Custom status code: \(code), message: \(message)")
default:
    print("Other status")
}

Main differences:

Attribute Raw Value Associated Value
Type Predefined (Int, String, etc.) Any type(s)
Association Tied to each element at declaration Tied to a specific instance of the element
Purpose Element identification Storing additional data of the element
Obligatoriness Optional Defined at the element declaration