Tarvo Mäesepp Tarvo Mäesepp - 1 month ago 8
Swift Question

Difference between error = error vs error != nil

I would like to know is there big difference between

if let error = error{}
vs
if error != nil
? Or is it just how people are different, like how they express themselves in code?

For example if I take this code:

user?.delete { error in
if let error = error {
print(error)
} else {

}


Because I can do the same like this and the output is the same:

user?.delete { error in
if error != nil {
print(error)
}else{

}


The only difference I can see other than "people are different" is that if I do not print error it would be better to use
if error != nil
because otherwise it would be declaring variable you do not use. Am I right?

Answer

As you already recognized at the end of your question, I would agree with you, that I would use if let, if I want to use the error variable to print it out for example. If I would just check if it's not nil and don't need the error variable, I would use if error != nil. You could also do if let _ = error, which is the same as if error != nil as Eric Aya mentioned in the comments of your question

Comments