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,

class Shape {
  var x:CGFloat = 0
  var y:CGFloat = 0
}

class Circle:Shape {
  var radius:CGFloat = 0
}

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.

enum Shapes {
 case Rect(CGFloat, CGFloat, CGFloat, CGFloat)
 case Circle(CGFloat, CGFloat, CGFloat)

 var path:UIBezierPath? {
   var bezier:UIBezierPath?=nil
   switch self {
     case .Rect(let x, let y, let wd, let ht):
       bezier = UIBezierPath(rect: CGRectMake(x, y, wd, ht))
     case .Circle(let x, let y, let radius):
       bezier = UIBezierPath(ovalInRect:CGRectMake(x-radius, y-radius, radius*2, radius*2))
     default:
       ()
   }
   return bezier
 }
 
 func render() {
   println("Render the shape")
   switch self {
     case .Rect(let x, let y, let wd, let ht):
       println("Rectangle -> [\(x), \(y), \(wd), \(ht)]")
     case .Circle(let x, let y, let radius):
       println("Circle -> [\(x), \(y), \(radius)]")
     default:
       println("Unknown Shape")
   }
 }

}

var rect1 = Shapes.Rect(10, 10, 150, 50)
var rectPath1 = rect1.path

var circle1 = Shapes.Circle(100, 100, 50)
var circlePath1 = circle1.path

var theShapes:[Shapes] = [rect1, circle1]

for shape in theShapes {
    shape.render()
}

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
1603
Views Today
Views Today
1
Posted in Basics, Tip, Tutorial.