假设您有代码
if stringValue == "ab" || stringValue == "bc" || stringValue == "cd" {
// do something
}
有没有办法缩短或美化这种情况(最好不使用switch语句)?我知道这段代码不起作用:
if stringValue == ("ab" || "bc" || "cd") {
// do something
}
我已经看到了一些其他语言的复杂解决方案,但它们似乎是特定于语言的,不适用于Swift。任何解决方案将不胜感激。
使用switch语句。
并不是我所知道的,尽管您可以做这样的事情,
上面的函数返回布尔值,然后您相应地编写逻辑。
您可以创建如下扩展名:
并像这样使用它:
Credit for the impl which saved me typing it: https://gist.github.com/daehn/73b6a08b062c81d8c74467c131f78b55/