loading...

Swift Enumerations (Part 3)

jaumevn profile image Jaume Viñas Navas ・2 min read

Swift enumerations are a first-class types in their own right, that means they can adopt many features traditionally supported only by classes. In this chapter we will cover how enumeration can define custom initializers to provide an initial case value, and how they can be extended and conform to protocols.

Remember to read the first chapters (Part 1 and Part 2) if you missed them or you want to refresh the basic concepts of Swift enums.

Protocols

A protocol defines an interface of methods, properties and other requirements that can be adopted by a class, structure or enumeration. Any type that satisfies the requirement of a protocol must provide an implementation of those requirements.

For demonstration purposes we use the LayerActions enumeration declared in the previous chapter, which defines a set of actions that users can execute in order to modify a layer in a design tool. To execute and describe each action we declare the protocol Taskable, which defines a method to execute a task and a description property that defines the task to be executed.

As you can see, the enumeration now conforms to the protocol requirements in the enumeration by implementing the method execute() and the computed property description.

Extensions

An extension adds new functionality to an existing class, structure, enumeration or protocol type. You can use an extension to add computed properties, define methods, define initializers, or make the existing type conform to a protocol among others.

In our case, we will extend the LayerActions enumeration to conform the protocol Taskable and make it easier to read, understand and maintain the code.

We can add as many extensions as we want, for instance, we can extend the previous enumeration in order to implement a different protocol. Here’s an example that extends the enumeration twice to separate the implementation of protocols Taskable and Serializable.

Initializers

Enumerations with a raw-value type automatically receive an initializer that takes as a parameter a value of the raw value’s type. Here’s an example of an enumeration with a raw-value type that uses the initializer to create a new instance.

Initilizers return either an enumeration case or nil. As you can see in the following example, the variable q is of type Polygon? and the value returned by the raw initializer is nil.

You can also create custom initializers even if the enumeration is not a raw-value typed enumeration.


If you find this post helpful, please recommend it for others to read.

Posted on by:

Discussion

markdown guide