What is the main difference between guard and if ... else?

I am confused when to use guardand when to use if...else.

Is protection a replacement or an alternative to an If statement? The main thing to know, what are the functional benefits of instructions guardfor Swift?

Any help to resolve this situation would be appreciated.

+4
source share
1 answer

Using protection may not seem very similar to using if, but with protection, your intention is more clear: execution should not continue if your conditions are not met. Plus, it has the advantage of being shorter and more readable, so security is a real improvement, and I'm sure it will be adopted quickly.

There is one bonus to using a protector that can make it even more useful to you: if you use it to expand any options, these expanded values ​​remain around so you can use them in the rest of your code block. For example:

   guard let unwrappedName = userName else {
return
}

print("Your username is \(unwrappedName)")

This is compared to the direct if statement, where the expanded value will be available only inside the if block, for example:

if let unwrappedName = userName {
print("Your username is \(unwrappedName)")
} else {
return
}

// this won't work – unwrappedName doesn't exist here!
print("Your username is \(unwrappedName)")

https://www.hackingwithswift.com/swift2

+13
source

Source: https://habr.com/ru/post/1623634/


All Articles