-1

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
            }
Deepak Sharma
  • 5,577
  • 7
  • 55
  • 131
  • I'm trying to duplicate the error because you haven't included it. Could you post enough for that? Specifically, `value` may be a bad name for a local variable. Maybe, if possible, let me know the *exact* build error? –  Aug 21 '20 at 12:23
  • What are you trying to express with the switch statement? What is `>f1..f1+f2` and `>f1+f2..<=1` supposed to mean? – Sweeper Aug 21 '20 at 12:25
  • I want the second case to be matched strictly for cases in the interval (f1, f1+f2] with f1 not included. – Deepak Sharma Aug 21 '20 at 13:45

1 Answers1

1

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:
vacawama
  • 150,663
  • 30
  • 266
  • 294