我不明白为什么它不能让我查看包含'在开关箱上

时间:2017-11-15 10:46:24

标签: swift

我试图做以下事情:

var stringwithcharactherTofind = "booboo$booboo"

switch stringwithcharactherTofind{
  case stringwithcharactherTofind.ifhasprefix("$"):
  stringwithcharactherTofind = "done"
  default:
  break
}

是否可以这样做?

完全

1 个答案:

答案 0 :(得分:2)

switch语句将给定值与给定模式匹配。 stringwithcharactherTofind.hasprefix("$")是一个布尔表达式 而不是字符串可以匹配的模式。

可以(ab)结合使用where子句 通配符模式:

let str = "FooBar"

switch str {
case _ where str.hasPrefix("Foo"):
    print("prefix")
case _ where str.contains("Foo"):
    print("contains")
default:
    print("nope")
}

甚至可以定义允许的模式匹配运算符 匹配一个布尔谓词的值(也证明了 here):

func ~=<T>(lhs: (T) -> Bool, rhs: T) -> Bool {
    return lhs(rhs)
}

let str = "FooBar"

switch str {
case { $0.hasPrefix("Foo") }:
    print("prefix")
case { $0.contains("Foo") }:
    print("contains")
default:
    print("nope")
}

但为什么要这么复杂呢?一个if/else if/else声明 完全符合您的要求:

if str.hasPrefix("Foo") {
    print("prefix")
} else if str.contains("Foo") {
    print("contains")
} else {
    print("nope")
}