Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use the range operator in a guard statement in Swift?

Tags:

swift

I'm trying to figure out an alternate way to do something like this, using the range operator.

guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 else {return}

Maybe something like this:

guard let statusCode = (response as? HTTPURLResponse)?.statusCode where (200...299).contains(statusCode) else {return}

or

guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode case 200...299 else {return}

Is this possible in Swift?

like image 916
Keith Grout Avatar asked May 14 '17 18:05

Keith Grout


People also ask

How do guard statements work in Swift?

In Swift, we use the guard statement to transfer program control out of scope when certain conditions are not met. The guard statement is similar to the if statement with one major difference. The if statement runs when a certain condition is met. However, the guard statement runs when a certain condition is not met.

What is the difference between a guard statement and an IF statement in Swift?

The main difference between guard and if statements in swift are: The if statement is used to run code when a condition is met. The guard statement is used to run code when a condition is not met.

What is range operator in Swift?

The closed range operator has an alternative form for ranges that continue as far as possible in one direction—for example, a range that includes all the elements of an array from index 2 to the end of the array. In these cases, you can omit the value from one side of the range operator.


1 Answers

As you like:

guard
    let statusCode = (response as? HTTPURLResponse)?.statusCode,
    (200...299).contains(statusCode) else {return}

or:

guard
    let statusCode = (response as? HTTPURLResponse)?.statusCode,
    case 200...299 = statusCode else {return}

or:

guard
    let statusCode = (response as? HTTPURLResponse)?.statusCode,
    200...299 ~= statusCode else {return}
like image 168
OOPer Avatar answered Oct 29 '22 02:10

OOPer