One way to use enums – just another day with Swift

Swift is quite interesting and is changing the way you would develop in the future. For this article, let’s look at using enums in an interesting manner.

What are we doing?

Say you want to create a program that allowed you to create shapes like Lines, Circles, Rectangles and RoundedRectangles. The way you would approach this is to create a class called say CustomShape and have a member called type that would let us know what type of shape is this.

The next step would be to have members to hold the variables in this shape class. However the issue is that the members required for each of the Shapes are different. So the way to manage this would be to have a base class or an abstract class and sub-class several classes inheriting from this base class. Like so,

This might not be the most efficient way but you can get the idea.

With Swift, enums could be used in a better fashion. This is just for illustration and there could be better ways to use this in your own code and applications.

These shapes can also be stored in an array of Shapes and you can iterate through the array and render each of them. For now the code above simply prints the shape type and the parameters. This is a simple example and could benefit with a class instead.

The problem is that you cannot update/change the parameters for the shapes. This is fixed and is part of the enum. The shape cannot be updated by simply updating any parameter, however you can add a variable of type Shape that is updated when you want to change the parameters of the Shape.

This may not be the best use case scenario for the use of enums but hopefully illustrates the point of using enums with Swift.

Views All Time
Views All Time
817
Views Today
Views Today
1
Posted in Basics, Tip, Tutorial.