问题描述
如何快速为 0,5,10
和 1,2,3,4,6,7,8,9:
创建范围
switch currentIndex {
case 0,10:
segment = .fullWidth
case 1,9:// Can't write infinity range here need formula
segment = .fiftyFifty
default:
segment = .fiftyFifty
}
example let underFive:Range = 0.0..<5.0
所以我可以把 underFive
放在 switch case 中。
解决方法
如果你想测试五的倍数
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
}
default
案例处理您的“无限范围”场景,因为 5、10、15 等的值由之前的 case
处理。
在回答您的问题时,范围由下限、上限或两者定义。 “部分范围”是具有下限或上限的范围,但不能同时具有两者。例如。 100...
是 100 或更大的整数。或者,结合“非五的倍数”逻辑:
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
}
但是范围本质上是由其上限和下限定义的。如果您希望排除某些数字,则必须将该逻辑放在较早的 case
中或添加一个 where
子句(或两者兼有)。或者使用 Set
而不是范围。
您问了一个关于常量/变量的单独问题。你可以很好地使用它:
let underFive = 0..<5
switch currentIndex {
case underFive: // under five
default: // five through 99
}
您只需确保范围的基础类型与 currentIndex
的类型匹配。
你可以使用
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)
此代码在操场上工作