ios-swift
/

Swift Enums – Beyond Simple Lists

Last Sync: Today

On this page

5
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

ios-swift

Swift Enums – Beyond Simple Lists

The Power of Swift Enums

In Swift, an enumeration defines a common type for a group of related values. However, they go much further than simple constants. Swift enums can have methods, computed properties, and initializers. As an Architect, you should use enums to model your application's domain logic, ensuring that invalid states are impossible to represent in your code.

  1. Basic Enums and Raw Values

You can back an enum with a 'Raw Value' such as a String or Integer. This is particularly useful for mapping API keys or database values to type-safe Swift code.

SWIFTRead-only
1
enum WidgetType: String {
    case button = "material_button"
    case textInput = "text_field"
    case image = "network_image"
}

let type = WidgetType.button
print(type.rawValue) // Output: "material_button"

  1. Associated Values (The State Killer)

Associated values allow you to attach extra information to an enum case. This is how Swift handles 'Result' types and complex UI states. In a Flutter context, this is similar to using 'Sealed Classes' for state management.

SWIFTRead-only
1
enum ProjectState {
    case idle
    case loading(progress: Double)
    case success(code: String)
    case failure(error: Error)
}

let currentState = ProjectState.loading(progress: 0.75)

switch currentState {
case .loading(let progress):
    print("Build progress: \(progress * 100)%")
case .success(let code):
    print("Generated: \(code)")
default:
    break
}

  1. CaseIterable and Methods

By conforming to the CaseIterable protocol, Swift automatically provides an allCases property, allowing you to loop through every case in the enum. You can also add methods to enums to give them behavior.

SWIFTRead-only
1
enum Theme: CaseIterable {
    case light, dark, system
    
    func getDescription() -> String {
        switch self {
        case .light: return "Bright and clear"
        case .dark: return "Easy on the eyes"
        case .system: return "Follows OS settings"
        }
    }
}

for theme in Theme.allCases {
    print(theme.getDescription())
}

Enums: Swift vs. Other Languages

FeatureSwift EnumsTraditional C/Java Enums
Backing TypeString, Int, Double, etc.Integers only
Custom DataAssociated Values (Per-case)Not supported
FunctionsSupported (Methods/Properties)Rarely supported
IterationNative (CaseIterable)Often manual
Pattern MatchingAdvanced (switch/if-case)Basic integer matching

Test Your Knowledge

Q1
of 3

Which protocol allows you to access a collection of all cases in an enum?

A
RawRepresentable
B
CaseIterable
C
Codable
D
Sequence
Q2
of 3

Which feature allows you to attach different types of data to specific enum cases at runtime?

A
Raw Values
B
Computed Properties
C
Associated Values
D
Extensions
Q3
of 3

True or False: In Swift, a switch statement must be exhaustive when used with an Enum.

A
True
B
False

Frequently Asked Questions

What is the difference between a Raw Value and an Associated Value?

Raw values are fixed values defined at compile-time for every case (like a String ID). Associated values are set at runtime when you create an instance of the case, allowing different instances of the same case to hold different data.

Can Enums have stored properties?

No. Swift enums cannot have 'stored' properties (variables that hold data across all cases), but they can have 'computed' properties that return a value based on the current case.

What are Recursive Enums?

An enum that has another instance of the same enum as an associated value. You must mark it with the 'indirect' keyword. This is useful for building tree structures like a nested UI widget hierarchy.

Previous

swift classes structs

Next

swift optionals

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.