-1

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.

Amit
  • 556
  • 1
  • 7
  • 24
  • @Rob I just want to make formula using `Range` `1,2,3,4,6,7,8,9:`. infinity means the range sequence can be long. not limited. – Amit Apr 03 '21 at 19:01
  • @Rob first will be 0,5,10,15,20.... and so on. vice versa in other case. how can I create `Range` object for that? – Amit Apr 03 '21 at 19:02
  • @Rob `x % 5` is great suggestion. But I am curious can we make formula for `1,2,3,4,6,7,8,9 .. so on:` so I can handle multiple switch cases also – Amit Apr 03 '21 at 19:07

2 Answers2

1

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.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
0

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

Rob
  • 415,655
  • 72
  • 787
  • 1,044