Swift —Why should I use the GUARD statement?

guard is a new conditional statement that requires execution to exit the current block if the condition isn’t met.

The guard statement puts the emphasis on the error condition. It makes your intent clearer: you tell guard what you want to be the case. guard is used specifically for trapping invalid parameters being passed to a method, so everyone will understand what it does when they see it.

Any optional variables unwrapped by guard remain in scope after the guard finishes, so you can use them. An optional variable can be checked if it’s valid by unwrapping it, then use it straight away.

Any conditions you would have checked using if before, you can now check using guard.

Show your support

Clapping shows how much you appreciated Irina Ernst’s story.