Last active
November 2, 2015 11:49
-
-
Save andr3a88/22738609b609c07c06eb to your computer and use it in GitHub Desktop.
Swift 2.0 Guard Statement
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Like an if statement, guard executes statements based on a Boolean value of an expression. | |
// Unlike an if statement, guard statements only run if the conditions are not met. | |
// You can think of guard more like an Assert, but rather than crashing, you can gracefully exit. | |
func fooGuardNonOptional(x: Int) { | |
guard x > 0 else { | |
// Value requirements not met, do something | |
return | |
} | |
// Do stuff with x | |
} | |
func fooGuard(x: Int?) { | |
guard let x = x where x > 0 else { | |
// Value requirements not met, do something | |
return | |
} | |
// Do stuff with x | |
x.description | |
} | |
func fooGuardBlock(x: Int?, block: () -> Void) { | |
guard let x = x where x > 0 else { | |
// Value requirements not met, do something | |
return | |
} | |
// Do stuff with x and call block() | |
block() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment