Earl Grey Earl Grey - 1 year ago 85
Swift Question

Is there a floating point type constrained to range 0 to 1 in Swift?

I am writing some convenience extensions to

One of the initialisers expects a Float from a range of 0 to 1 to set transparency.
I am looking for sort of equivalent to
. This is an integer constrained to range 0 - 255.
Is there a native type that would allow any unsigned float from range 0 to 1?

Answer Source

There is no way you can constraint this range. I would suggest asserting the parameters:

let allowedRange = 0.0...1.0

That indicates that that bad input is not allowed. Or throw an error that you can recover from elsewhere:

let allowedRange = 0.0...1.0
guard allowedRange.contains(red) else {
    throw NSError(domain: "YourDomain", code: 0, userInfo: [:])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download