切换语句,其中value为Int但case可以包含数组 [英] Switch statement where value is Int but case can contain array

查看:123
本文介绍了切换语句,其中value为Int但case可以包含数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想把我的数组值作为我的switch语句的一个案例

I want to put my array of values as a case for my switch statement

我有一个值数组说

let intValues = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 .... 100]

我想使用switch语句用作比较工具,如此。

and I want to use a switch statement to be used as a comparison tool like so.

let inputValue = 30 // or some other int value
switch inputValue {
case 101:
    // do something lol

/* ===============================  */
case intValues: // 
    // do something more:
/* ===============================  */

case 13131: 
    // do another thing
default:
    // do default
}

我知道我可以通过这样做很容易地做到这一点案例1,2,3,4,5,依此类推,或者使用 if语句,如下所示:

I know I can do this easily by either doing this case 1, 2, 3, 4, 5, and so on or by using an if statement like so:

if intValues.contains(inputValue) {
     // do something more:
} else if inputValue == 101 {
     // do something lol
} else if inputValue == 13131 {
     // do another thing
} else {
     // do default 
}

或做一些像

if intValues.contains(inputValue) {
     // do something more:
} else {
    switch inputValue {
    case 101:
       // do something lol
    case 13131: 
       // do another thing
    default:
       // do default
    }
}

反之亦然

但是有可能吗?仅使用switch语句来执行此操作?

But is it possible though? to do it with just a switch statement?

推荐答案

您可以使用 case let 其中

let intValues = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
let inputValue = 30 // or some other int value
switch inputValue {
    case let x where intValues.contains(x):
        // do something more:
    case 101:
        // do something lol
    case 13131:
        // do another thing       
    default:
        // do default 
}

这篇关于切换语句,其中value为Int但case可以包含数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆