Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Enumeration Methods in Swift
Written by Team Kodeco

In Swift, enumerations can have methods just like classes and structs. These methods can be used to provide additional functionality specific to the enumeration’s cases.

The syntax for declaring a method on an enumeration is similar to that of a class or struct. Here is an example of an enumeration with a method called description:

enum Shape {
  case square(side: Double)
  case rectangle(width: Double, height: Double)
  case circle(radius: Double)

  func description() -> String {
    switch self {
    case .square(let side):
      return "A square with side of length \(side)"
    case .rectangle(let width, let height):
      return "A rectangle with width \(width) and height \(height)"
    case .circle(let radius):
      return "A circle with radius \(radius)"
    }
  }
}

You can call methods on an enumeration case the same way as you call methods on a class or struct. For example, you can call the description method on a Shape enumeration as follows:

let square = Shape.square(side: 2.0)
print(square.description()) // prints "A square with side of length 2.0"
© 2024 Kodeco Inc.