Swift如何检查多个字符串条件的变量

时间:2016-04-26 21:16:57

标签: string swift dictionary

目前我正在检查字典中的某个键是否包含某个字符串值:

if dict["eventCode"] == "OFF" || dict["eventCode"] == "DHD" || dict["eventCode"] == "SBY"
  {
     // do something
  }
else if dict["eventCode"] == "DHT" || dict["eventCode"] == "SLV" || dict["eventCode"] == "CLV"
 {
   // do something else
}

可能的值列表大约为10,if语句工作但很长,容易出现类型错误。

折射这种“if语句”的最佳方法是什么?

3 个答案:

答案 0 :(得分:3)

String上的

switch

guard let val = dict["eventCode"] as? String else { return }

switch val {
case "OFF", "DHD", "SBY":
    print("something")

case "DHT", "SLV", "CLV":
    print("something else")

default:
    print("default")
}

答案 1 :(得分:2)

let check1 = ["OFF", "DHD", "SBY"]
let check2 = ["DHT", "SLV", "CLV"]

if check1.contains(dict["eventCode"] ?? "") {
    print("found in 1")
} else if check2.contains(dict["eventCode"] ?? "") {
    print("found in 2")
}

但在我看来,这看起来很丑..

答案 2 :(得分:1)

我通常使用switch声明:

switch dict["eventCode"] {
    case let ec? where ec == "OFF" || ec == "DHD" || ec == "SBY":
        // do something
    case let ec? where ec == "DHT" || ec == "SLV" || ec == "CLV":
        // do something else
    default:
        break 
}

虽然它不一定比一系列if-else分支更少的代码,但我发现逻辑更清晰,更容易阅读。

编辑:

@ Eendje的答案也非常好,可以与switch结合使用:

let check1 = ["OFF", "DHD", "SBY"]
let check2 = ["DHT", "SLV", "CLV"]

switch dict["eventCode"] {
    case let ec? where check1.contains(ec):
        // do something
    case let ec? where check2.contains(ec):
        // do something else
    default:
        break 
}