Last active
February 23, 2017 11:03
-
-
Save ecerney/d6bfed963eede7c685a0 to your computer and use it in GitHub Desktop.
Guard argument
This file contains hidden or 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
/* | |
* For a more in depth look at the guard statement check out | |
* http://ericcerney.com/swift-guard-statement/ | |
* where I build off the sample shown here. | |
*/ | |
var x: Int? = 0 | |
// Lets me unwrap x and also check a condition on it | |
func fooGuard() { | |
guard let x = x where x > 0 else { | |
return | |
} | |
// Do stuff with x | |
x.value | |
} | |
// I have to check it exists and force unwrap to check the condition. | |
// I also need to check the bad case rather than checking that its the good case. | |
// `x! <= 0` rather than `x! >= 0` | |
func fooManualCheck() { | |
if x == nil || x! <= 0 { | |
return | |
} | |
// Do stuff with x | |
x!.value | |
} | |
// I am not doing early exiting here, but rather the bulk of code is done in the binding | |
func fooBinding() { | |
if let x = x where x > 0 { | |
// Do stuff with x | |
x.value | |
} | |
return | |
} | |
let y = 23 | |
func fooNonOptional() { | |
guard y > 0 else { | |
return | |
} | |
//Do whatever you want with y since its valid | |
} | |
func fooNonOptional2() { | |
if y <= 0 { | |
return | |
} | |
//Do whatever you want with y since its valid | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment