Enums group related values together. Methods and computed properties add useful actions and information to each enum case.
0
0
Enum methods and computed properties in Swift
Introduction
When you want to add a function that works differently for each enum case.
When you want to calculate a value based on the enum case without storing it.
When you want to keep related code organized inside the enum.
When you want to describe or format enum cases in a custom way.
When you want to add helper features to enum cases for easier use.
Syntax
Swift
enum EnumName { case case1 case case2 func methodName() -> ReturnType { // code using self to act based on case } var computedPropertyName: ReturnType { // code returning a value based on self } }
Use func inside enums to add methods.
Use var with a computed getter to add computed properties.
Examples
A method
description() returns a string for each direction.Swift
enum Direction { case north, south, east, west func description() -> String { switch self { case .north: return "Up" case .south: return "Down" case .east: return "Right" case .west: return "Left" } } }
A computed property
isSafeToGo returns true only for green light.Swift
enum Light { case red, yellow, green var isSafeToGo: Bool { return self == .green } }
Computed property converts any temperature to Celsius.
Swift
enum Temperature { case celsius(Double) case fahrenheit(Double) var inCelsius: Double { switch self { case .celsius(let value): return value case .fahrenheit(let value): return (value - 32) * 5 / 9 } } }
Sample Program
This program defines an enum Mood with a method emoji() and a computed property description. It prints the emoji and description for the current mood.
Swift
enum Mood { case happy, sad, angry func emoji() -> String { switch self { case .happy: return "😊" case .sad: return "😢" case .angry: return "😠" } } var description: String { switch self { case .happy: return "Feeling good" case .sad: return "Feeling down" case .angry: return "Feeling mad" } } } let currentMood = Mood.happy print("Mood emoji: \(currentMood.emoji())") print("Mood description: \(currentMood.description)")
OutputSuccess
Important Notes
Use self inside methods and computed properties to refer to the current enum case.
Computed properties do not store values; they calculate and return them when accessed.
Methods can take parameters and return values, just like functions outside enums.
Summary
Enums can have methods to perform actions based on cases.
Computed properties provide calculated values related to enum cases.
These features help keep related code organized and clear.