是否可以使用范围运算符 ...
和 ..<
用 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 ... 299
或 200 ..< 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/