Advanced Enum in Swift

Tram Ho

1. Properties

Enum cannot create stored properties in enum, but can contain computed properties.

Now create an enum named Device, it contains a computed property named year, which returns the year of birth of that device.

2. Methods

We can also define methods in an enum.

The following example uses the main switch of cases in the device enum to print out the production year of that divce:

3. Nested Enums

We can create an enum inside an enum, which allows for more structured and clear code.

4. Containing Enums

We can embed enum into struct or class.

4.1 Create a struct containing enum

For example, when making a game, we need to create a character, have weapons and “class”:

4.2 Initialization

To init a new character, we must select the “class” and the weapon type:

5. Mutating Method

Create a mutating function that can change the case into another case to use in special cases. The following example defines an enum for three speeds of a fan:

6. Static Method

We can also create static methods in enum. The following example creates an enum named Device, which contains a static funtion that returns the enum Device based on the device name entered from the parameter of the static function:

7. Custom Init

Create a custom initialization method:

8. Protocol Oriented Enum

We can also conform to a protocol with enum.

To understand how to conform to the enum protocol. We will create a game in which a player can have 2 .dead or .alive states. When .alive, the player has health, and life stats. If these stats reach zero, the player will die (.dead):

8.1 Create Protocol

Let’s create a protocol called, LifeSpan. It contains one property, numberOfHearts and two mutating functions which will be used to increase / decrease a player’s heart. Create a protocol called LifeSpan, which contains 1 property – numberOfHearts and 2 mutating functions that will be used to increase or decrease the player’s health index:

8.2 Create Enum

Now, create an Player enum, conform to the LifeSpan protocol, have 2 cases, .alive or .dead, .alive case assigned with the current blood index – currentHeart. A computed property calculates the character’s health index – numberOfHearts, based on the player’s .dead or .alive status.

8.3 Play Game

Let’s play the game.

9. Extensions

We can also create an enum extension to add properties and methods:

10. Generic Enums

We can also create generic enum:

Init:

let info = Information.name("Bob") // Error

The compiler reports an error because we just said T1 is a String based on the string “Bob”. However, the data type of T2 has not been defined. Therefore, we must define both T1 and T2 types:

Share the news now

Source : Viblo