← Back to archive

Development · Swift

Swift enums and raw values

Model related choices with enums and use type inference and raw values to work with valid states.

Read the Korean original on Velog ↗English translation

Development archive cover

An enum groups related choices into one type. Compared with passing arbitrary strings, it makes the allowed values explicit and catches invalid usage at compile time.

Group related choices in a type

enum DevelopmentRole {
    case frontend
    case backend
    case app
}

func introduce(role: DevelopmentRole) {
    print("My role is \(role)")
}

introduce(role: .app)

When the type is already known, Swift lets you write .app instead of DevelopmentRole.app.

Associating raw values

enum DevelopmentRole: String {
    case frontend = "프론트엔드"
    case backend = "백엔드"
    case app = "앱"
}

print(DevelopmentRole.app.rawValue) // App
let role = DevelopmentRole(rawValue: "앱") // DevelopmentRole?

Initialization from a raw value returns an optional because a matching case may not exist. An enum is more than a set of constants: it represents the valid states and rules of a domain.

← Back to archive