Swift enum - limit bound values

I have an enumeration that represents the thickness of a line, which can be either a constant width or a width relative to the size of the view.

enum Thickness {
    case Constant(Float)    // where value ≥ 0
    case Relative(Float)    // where 0 ≤ value ≤ 1
}

Is there a way to build these related value constraints into an enum type? I am currently using didSetproperty observers for properties of this type:

var lineThickness: Thickness {
    didSet {
        switch lineThickness {
            case let .Relative(x): lineThickness = .Relative(min(max(x, 0), 1))
            case let .Constant(x): lineThickness = .Constant(max(x, 0))
        }
    }
}

But it would be far ahead if I could do this once for the whole type and not replicate this observer for each property.

I know that I can create initializers or methods for enumeration, but I'm not sure that / how could I use this to limit the bound value?

+4
source share
1

, , , , - ...

struct Thickness {
    enum Type {
        case Constant
        case Relative
    }
    let type: Type
    let value: Float

    init(type: Type, value: Float) {
        self.type = type;
        switch type {
            case .Constant:
                self.value = max(value, 0)
            case .Relative:
                self.value = min(max(value, 0), 1)
        }
    }
}
+2

Source: https://habr.com/ru/post/1570833/


All Articles