Skip to content

Instantly share code, notes, and snippets.

@simonkim
Created September 26, 2016 01:35
Show Gist options
  • Save simonkim/967e2536e34f00633d226e1ff18f6aaf to your computer and use it in GitHub Desktop.
Save simonkim/967e2536e34f00633d226e1ff18f6aaf to your computer and use it in GitHub Desktop.
guard let vs. if nil
//: guard let example
func printifnonnil(text: String?) {
if text == nil {
return
}
// syntatically, unwrapping still required since text is still an optional
print(text!)
}
func printguard(text: String?) {
guard let text = text else {
return
}
// guranteed that text is not an optional
print(text)
}
printifnonnil(text: "hello")
printifnonnil(text: nil)
printguard(text: "hello")
printguard(text: nil)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment