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?
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.
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.
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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With