How to create range in swift for switch case.?

1k views Asked by At

How to create range in swift for 0,5,10 & 1,2,3,4,6,7,8,9:

 switch currentIndex {
        case 0,5,10:
            segment = .fullWidth
        case 1,2,3,4,6,7,8,9:// Can't write infinity range here need formula
            segment = .fiftyFifty
        default:
            segment = .fiftyFifty
        }

example let underFive:Range = 0.0..<5.0 so I can put underFive in switch case.

2

There are 2 answers

0
Владимир Ковальчук On

You can use

var currentIndex = 4
enum Segment {
    case nothing
    case fullWidth
    case fiftyFifty
}

var segment: Segment = .nothing

switch currentIndex {
case 0,5,10:
      segment = .fullWidth
case 1...4, 6...9 :
      segment = .fiftyFifty
default:
      segment = .fiftyFifty
}

print(segment)

this code work in playground

enter image description here

1
Rob On

If you want a test for multiples of fives

switch currentIndex {
case let x where x.isMultiple(of: 5): // multiples of five here
default:                              // if you reach here, every value not divisible by five
}

The default case handles your “infinite range” scenario because the values of 5, 10, 15, etc., were handled by the prior case.

In answer to your question, a range is defined by a lower bound, an upper bound, or both. A “partial range” is one that has a lower bound or an upper bound, but not both. E.g. 100... is all integers 100 or larger. Or, combining with the “not multiple of five” logic:

switch currentIndex {
case let x where x.isMultiple(of: 5): // multiples of five here
case 100...:                          // non multiples of five that are 100 or more
default:                              // everything else
}

But a range is inherently defined by its upper and lower bounds. If there numbers you wish to exclude, you have to put that logic in an earlier case or add a where clause (or both). Or use Set rather than ranges.


You asked a separate question about constants/variables. You can use that fine:

let underFive = 0..<5

switch currentIndex {
case underFive:                       // under five
default:                              // five through 99
}

You only need to make sure that the underlying type of your range matches the type of the currentIndex.