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相关问答推荐

SWIFT并发:合并Taskgroup和AsyncStream?

ARRaycast Query和前置摄像头(ARFaceTrackingConfiguration)

我可以为UIMenu设定一个固定的订单吗?

RealityKit - 从中心zoom 模型

在 SwiftUI 中禁用 Select 器选项

Swift 包管理器 Package.resolved 文件末尾的版本是什么意思?

SwiftUI:当 currentIndex 值更改时,数组中的第 n 个视图是否已换出?

Swift UI 不重绘 NSViewRepresentable 包装的文本字段

SwiftUI 中的计时器崩溃屏幕

更改该函数的参数之一时,如何将这些 SwiftUI 异步任务合并到一个任务中以从函数中获得正确的结果

如何在 Swift 中返回 Task 中定义的变量

在 SwiftUI 中,如何在 UIView 内或作为 UIView 使用 UIHostingController?

iOS Swift - 如何更改表格视图的背景 colored颜色 ?

Swift 动画 WithDuration 语法是什么?

如何轻松删除领域中的所有对象

Swift:如何从函数返回类类型

Swift 3:日期与 NSDate?

UISearchbar TextField 的高度可以修改吗?

无法将 NSAttributedString.DocumentAttributeKey 类型的值转换为 .DocumentReadingOptionKey

从 Swift 初始化程序调用方法