enum Basics / case / switch
Swift's enum (enumeration) defines a group of related values as a type. Swift enums are powerful — they can have methods and properties.
Syntax
// Basic enum definition
enum EnumName {
case caseName1
case caseName2
case caseName3, caseName4 // Multiple cases can be defined on one line
}
// CaseIterable: allows you to get all cases as an array
enum EnumName: CaseIterable {
case caseName1
case caseName2
}
Syntax Reference
| Syntax | Description |
|---|---|
| enum Name { case ... } | Defines an enumeration type. |
| case caseName | Defines each case of the enumeration. |
| Exhaustive matching with switch | A switch statement on an enum must cover all cases. |
| CaseIterable | Conforming to this protocol lets you access all cases via the allCases property. |
| EnumName.allCases | Returns an array of all cases (requires CaseIterable conformance). |
Sample Code
// Basic enum
enum Direction {
case north
case south
case east
case west
}
// Usage
var heading = Direction.north
heading = .east // Type can be omitted when it's already known
// Exhaustive matching with switch
switch heading {
case .north:
print("Heading north")
case .south:
print("Heading south")
case .east:
print("Heading east")
case .west:
print("Heading west")
}
// Iterate over all cases with CaseIterable
enum Season: CaseIterable {
case spring, summer, autumn, winter
}
print("Number of seasons: \(Season.allCases.count)")
for season in Season.allCases {
print(season)
}
// Comparison (== / !=)
let day = Direction.north
if day == .north {
print("Heading north")
}
Overview
Unlike C enumerations, Swift's enum is not just an integer alias. It can have methods and properties, and can conform to protocols.
When you use a switch statement on an enum, the compiler checks that all cases are covered. This means any missed cases when a new case is added are caught at compile time.An enum is a value type (like a struct) and is not passed by reference the way a class is.
For enums with raw values (RawValue), see enum RawValue (Int / String).
If you find any errors or copyright issues, please contact us.