Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using guard to check for nil without implicitly unwrapping

Tags:

swift

I know there are some similar questions around, but I couldn't find one specific to my issue. I have a request where I want to check for the presence of the error key. it is not present everything is fine, if not I should handle the error. Currently, I have it implemented as follows:

if let error = json["error"] {
    // handle error
}
else {
    // handle success
}

I would like to use a guard statement here to have the success case unindented. The only way I came up with is

guard json["error"] == nil else {
    let error = json["error"]!
    // handle error
} 

// handle success

but that seems wrong to me with the !. Are there any other approaches to this?

like image 633
warly Avatar asked Jan 18 '17 10:01

warly


People also ask

What kind of error occurs when you force unwrap an optional that contains nil?

It's called implicitly unwrapped since Swift force unwraps it every time. The drawback of this is same as forced unwrapping - if the value is nil when accessing, it leads to a fatal error. Similar to optionals, optional binding and optional chaining can also be used for implicitly unwrapped optionals.

What does thread 1 fatal error unexpectedly found nil while implicitly unwrapping an optional value mean?

It means that something was nil where it should not be. how I can fix the error. Check all the place you use Implicitly Unwrapped Optional type (!) and forced unwrapping (!). In your code shown, there are no forced unwrappings, so you may have some properties with Implicitly Unwrapped Optional type.

What is a guard statement What is the benefit of using the guard statement 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.


1 Answers

In your guard code you would have to have a return statement in the else block. Like this...

guard json["error"] == nil else {
    let error = json["error"]!
    // handle error
    return
}

// handle success

But you are correct. Having to force unwrap the error is not ideal.

So in this case. I think guard is the wrong solution. Instead use if but return from the conditional block. This removes the need for using an else block.

if let error = json["error"] {
    print(error)
    // handle error
    return
}

// handle success...
// no need for else block. Just return from the if in the error case.

The difference between guard let and if let is where the unwrapped optional is scoped.

With guard it is scoped outside the block with if it is scoped inside the block.

like image 182
Fogmeister Avatar answered Sep 30 '22 05:09

Fogmeister