微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何快速为开关盒创建范围?

如何解决如何快速为开关盒创建范围?

如何快速0,5,101,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)

此代码在操场上工作

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。