Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guard vs If Not

Tags:

swift

I know what guard does in Swift. I have read the questions about using guard or if let. However, is there any difference between guard (condition) else { return } and if !condition { return }? They seem to do the same thing.

EDIT: This was not asking about guard let and if let. I now know that guard let is a more useful usage of guard. I was simply asking about the differences between a simple guard and if.

like image 293
Derek Kaplan Avatar asked Aug 31 '25 05:08

Derek Kaplan


1 Answers

There is a difference if you need to declare a variable in the guard statement, i.e.

guard let foo = bar else { return }

In this case, you can continue to use foo as a non-optional in the rest of the method. You can't do this with a simple if statement.

If you're wondering why that's handy:

if let because = nobody {
    if let likes = pyramids {
        if let of = doom {
            // guard can help you avoid this!
        }
    }
}
like image 102
Charles Srstka Avatar answered Sep 02 '25 18:09

Charles Srstka