Junior — Middle
Is it possible to extend the functionality of enumerations by adding methods to them?
sobes.tech AI
Answer from AI
In Swift, enumerations (enums) can contain not only a set of values but also methods, properties, and even initializers. This allows extending the functionality of enums by adding methods for handling values or performing logic related to specific cases.
Example:
enum Direction {
case north, south, east, west
func description() -> String {
switch self {
case .north: return "North"
case .south: return "South"
case .east: return "East"
case .west: return "West"
}
}
}
let dir = Direction.north
print(dir.description()) // Outputs: North
Thus, yes, in Swift, you can extend enums with methods for convenience and logical grouping of related functionality.