Cadence OOPs Mastery: Enumerations

Enumerations

Enumerations are sets of symbolic names bound to unique, constant values, which can be compared by identity.

Enum Declaration

Enums are declared using the enum keyword, followed by the name of the enum, the raw type after a colon, and the requirements, which must be enclosed in opening and closing braces.

Enum cases are declared using the case keyword, followed by the name of the enum case. Enum cases must be unique. Each enum case has a raw value, the index of the case in all cases.

The enum cases can be accessed by using the name as a field on the enum, or by using the enum constructor, which requires providing the raw value as an argument. The enum constructor returns the enum case with the given raw value, if any, or nil if no such case exists.

Enum cases can be compared using the equality operators == and !=.

pub enum Color: UInt8 {

pub case red

pub case blue

}

let blue: Color = Color.blue

// Get the raw value of the enum case blue.

// As it is the third case, so it has index 1

//blue.rawValue // is 2