iosswiftswitch-statementswift5nsrange

Swift range check > in switch


The following code doesn't compile in Swift. What is the best way to alternatively express it?

   //f1 & f2 are float vars between 0 & 1

   switch value {
            case 0...f1:
                break
            case >f1..f1+f2:
                break
            case >f1+f2..<=1:
                break
            default:
                break
            }

Solution

  • It is not possible to create a range in Swift that is open on the low end.

    This will accomplish what you intended:

    switch value {
    case 0...f1:
        print("one")
    case f1...(f1 + f2):
        print("two")
    case (f1 + f2)...1:
        print("three")
    default:
        print("four")
    }
    

    Since switch matches the first case it finds, you don't have to worry about being non-inclusive on the low end. f1 will get matched by the "one" case, so it doesn't matter that the "two" case also includes it.

    If you wanted to make the first case exclude 0, you could write it like this:

    case let x where 0...f1 ~= x && x != 0:
    

    or

    case let x where x > 0 && x <= f1: