swift-enumerations (3 Part Series)
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.
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
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
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
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.
Level up every day