Skip to content

Instantly share code, notes, and snippets.

@andr3a88
Last active November 2, 2015 11:49
Show Gist options
  • Save andr3a88/22738609b609c07c06eb to your computer and use it in GitHub Desktop.
Save andr3a88/22738609b609c07c06eb to your computer and use it in GitHub Desktop.
Swift 2.0 Guard Statement
// 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