我可以在 Swift 中将范围运算符与 if 语句一起使用吗? [英] Can I use the range operator with if statement in Swift?

查看:24
本文介绍了我可以在 Swift 中将范围运算符与 if 语句一起使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

让 statusCode = 204如果 statusCode 在 200 ..<299 {NSLog("成功")}

解决方案

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

if 200 ... 299 ~= statusCode {打印(成功")}

或者带有表达式模式的 switch 语句(使用模式匹配内部操作符):

开关状态码{案例 200 ... 299:打印(成功")默认:打印(失败")}

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

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

if 200 ... 299 ~= statusCode

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

addq $-200, %rdicmpq 99 美元,%rdija LBB0_1

这是为

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

if statusCode >= 200 &&状态代码 <= 299

你可以用

验证<前>xcrun -sdk macosx swiftc -O -emit-assembly main.swift

从 Swift 2 开始,这可以写成

if case 200 ... 299 = statusCode {打印(成功")}

对 if 语句使用新引入的模式匹配.另请参阅 Swift 2 - if"中的模式匹配.

Is it possible to use the range operator ... and ..< with if statement. Maye something like this:

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

解决方案

You can use the "pattern-match" operator ~=:

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

Or a switch-statement with an expression pattern (which uses the pattern-match operator internally):

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

Note that ..< denotes a range that omits the upper value, so you probably want 200 ... 299 or 200 ..< 300.

Additional information: When the above code is compiled in Xcode 6.3 with optimizations switch on, then for the test

if 200 ... 299 ~= statusCode

actually no function call is generated at all, only three assembly instruction:

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

this is exactly the same assembly code that is generated for

if statusCode >= 200 && statusCode <= 299

You can verify that with

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")
}

using the newly introduced pattern-matching for if-statements. See also Swift 2 - Pattern matching in "if".

这篇关于我可以在 Swift 中将范围运算符与 if 语句一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆