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 Methods / Properties / mutating

enum Methods / Properties / mutating

In Swift, enums can have methods and computed properties. Methods that modify the enum's own case require the mutating keyword.

Syntax

enum EnumName {
    case case1
    case case2

    // Computed property
    var propertyName: Type {
        switch self {
        case .case1: return value1
        case .case2: return value2
        }
    }

    // Method
    func methodName() {
        // Process
    }

    // Method that modifies self (mutating)
    mutating func mutatingMethod() {
        self = .case2
    }
}

Syntax Reference

SyntaxDescription
var property: Type { ... }Defines a computed property.
func methodName() { ... }Defines a regular instance method.
mutating func methodName()Defines a method that modifies the enum's own case.
static func methodName()Defines a type method.
indirect enumDefines a recursive enum (required when a case references the enum itself).

Sample Code

// An enum with methods and properties
enum TrafficLight {
    case red, yellow, green

    // Computed property
    var waitSeconds: Int {
        switch self {
        case .red:    return 60
        case .yellow: return 5
        case .green:  return 45
        }
    }

    var canGo: Bool {
        return self == .green
    }

    // Instance method
    func description() -> String {
        switch self {
        case .red:    return "Stop"
        case .yellow: return "Caution"
        case .green:  return "Go"
        }
    }

    // mutating: advance to the next case
    mutating func next() {
        switch self {
        case .red:    self = .green
        case .green:  self = .yellow
        case .yellow: self = .red
        }
    }
}

var light = TrafficLight.red
print("\(light.description()) - Wait: \(light.waitSeconds)s")
print("Can go: \(light.canGo)")

light.next()
print("Next: \(light.description())")

light.next()
print("Next: \(light.description())")

Overview

By adding methods and properties to an enum, you can group all logic related to each case in one place. Encapsulating switch-case statements inside methods keeps the calling code simple and readable.

Because enums are value types, any method that modifies the enum's own case requires the mutating keyword. Computed properties are supported, but stored properties (such as var x: Int = 0) are not allowed inside an enum.

For the basics of enums, see enum basics / case / switch.

If you find any errors or copyright issues, please .