if-statement - 我可以在 Swift 中将范围运算符与 if 语句一起使用吗?

标签 if-statement swift range

是否可以使用范围运算符 .....<用 if 语句。可能是这样的:

let statusCode = 204
if statusCode in 200 ..< 299 {
  NSLog("Success")
}

最佳答案

您可以使用“模式匹配”运算符 ~= :

if 200 ... 299 ~= statusCode {
    print("success")
}

或者带有表达式模式的 switch 语句(使用模式匹配 内部运营商):

switch statusCode {
case 200 ... 299:
    print("success")
default:
    print("failure")
}

请注意 ..<表示省略上限值的范围,因此您可能想要 200 ... 299200 ..< 300 .

附加信息:当上述代码在 Xcode 6.3 中编译时 开启优化,然后进行测试

if 200 ... 299 ~= statusCode

实际上根本没有生成函数调用,只有三个汇编指令:

addq    $-200, %rdi
cmpq    $99, %rdi
ja  LBB0_1

这与生成的汇编代码完全相同

if statusCode >= 200 && statusCode <= 299

你可以验证

xcrun -sdk macosx swiftc -O -emit-assembly main.swift

As of Swift 2, this can be written as

if case 200 ... 299 = statusCode {
    print("success")
}

对 if 语句使用新引入的模式匹配。 另见 Swift 2 - Pattern matching in "if" .

关于if-statement - 我可以在 Swift 中将范围运算符与 if 语句一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24893110/

相关文章:

ios - Swift - 加载搜索结果时的并发问题。我加载图像,发送请求,但请求为时已晚

json - 在 swift 中使用字典和 utf-8 发出发布请求

vba - Excel VBA 选择 - 更好的代码

bash - 在 bash 中生成大小写范围

OCaml "else"语法错误

r - 如何匹配不正确的字符串并替换为正确的字符串

ios - 使用 Openweathermap 获取名称中包含空格的城市的天气

python - 为什么我不必使用 range() 在 for 循环中定义变量,但我必须在 Python 的 while 循环中定义变量?

java - if循环不会停止循环

C - Switch 语句与员工薪酬的 If 语句?