Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use the range operator with if statement in Swift?

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")
}
like image 354
Jimmy Avatar asked Oct 18 '22 07:10

Jimmy


People also ask

How many types of range operators are there in Swift?

Types of Range in Swift In Swift, there are three types of range: Closed Range. Half-Open Range. One-Sided Range.

How does range work in Swift?

Ranges in Swift allow us to select parts of Strings, collections, and other types. They're the Swift variant of NSRange which we know from Objective-C although they're not exactly the same in usage, as I'll explain in this blog post. Ranges allow us to write elegant Swift code by making use of the range operator.

Which operator is used to test whether a given value is included in the range?

operator. Returns a Boolean value indicating whether a value is included in a range.


1 Answers

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".

like image 462
Martin R Avatar answered Oct 19 '22 21:10

Martin R