Home > Software design >  How do I convert an integer to an enum based on its range in Swift?
How do I convert an integer to an enum based on its range in Swift?

Time:11-17

Is there a way to convert an integer to an enum based on its value range? For the sake of elegance, I prefer to implement it into an enum or auxiliary type rather than as a separate function. Ideally, it would be great if I could perform the conversion using a cast like so:

let readPosition = Position(controller.readVal())

or

let readPosition = (Position) controller.readVal()

Below is my feeble attempt at it:

// Should be sealed, yet extensible, c# has sealed, but not Swift
public enum Position: Int {
    case Both = 0, Bottom = 1, Top = 2
}

// Position should not be changed to preserve compatibility. 
// Different converters will be implemented by different apps
// overtime.
extension Position {
    static func convert(val: Int64?) -> Position {
        switch val {
            case .some(1), .some(..<8):
                return Position.Top
            case .some(2), .some(8...):
                return Position.Bottom
            default:
                return Position.Both
        }
    }
}

CodePudding user response:

You already have all you need, you can now define an initializer:

extension Position {
    init(_ val: Int64) {
       self = Self.convert(val)
    }
}

Then you can use your requested:

let readPosition = Position(controller.readVal())
  • Related