Advanced and Practical Enum usage in Swift

UIKit Identifiers

released Fri, 01 Mar 2019
Swift Version 5.0

Units

Units and unit conversion are another nice use case for enums. You can map the units and their respective values and then add methods to do automatic conversions. Here's an oversimplified example.

enum Liquid: Float {

   case ml = 1.0

   case l = 1000.0

   func convert(amount: Float, to: Liquid) -> Float {

       if self.rawValue < to.rawValue {

          return (self.rawValue / to.rawValue) * amount

       } else {

          return (self.rawValue * to.rawValue) * amount

       }

   }

}

Another example of this would be Currency conversion. Also, mathematical symbols (such as degrees vs radians) can benefit from this.