我试图做以下事情:
var stringwithcharactherTofind = "booboo$booboo"
switch stringwithcharactherTofind{
case stringwithcharactherTofind.ifhasprefix("$"):
stringwithcharactherTofind = "done"
default:
break
}
是否可以这样做?
完全
答案 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")
}