Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Swift Dictionary

  1. Home
  2. Swift Dictionary
  3. enum Basics / case / switch

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

SyntaxDescription
enum Name { case ... }Defines an enumeration type.
case caseNameDefines each case of the enumeration.
Exhaustive matching with switchA switch statement on an enum must cover all cases.
CaseIterableConforming to this protocol lets you access all cases via the allCases property.
EnumName.allCasesReturns 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 .