Guard is the number one thing you can do to make you code look and feel pro!
Big statement? Yes, but after you start using guard you will find your code is better in almost every way!
I don't care how my code looks! It just works.
Bullshit! Pretty code is good code!
You are going to make pretty code, and the pretty code will make better apps!
Guard is ugly, and so is your code!
Now you're just being ridiculous. Guards are awesome. I'll show you why!
Why guard is awesome
Let's say we have a function that takes in an optional array...
func DoSomething(array:[Int]?) {
if let strongArray = array {
//Do something to the array
}
}
Now with guard!
func DoSomething(array:[Int]?) {
guard let strongArray = array
else {
return
}
//Do something to the array
}
Notice the difference?
It's longer?
Try again!
The code isn't inside the {...}?
Bingo!
Why do I care?
If let is awesome and powerful. The only downside is that the important code always goes inside the {}. That's bad simply because it is harder to read the code.
example?
You asked for it!
func DoSomething(dictionary:[String : Any]?) {
if let dict = dictionary {
if dict.keys.contains("first") {
if let first = dict["first"] as? String {
let second = "legs"
if first == "frog" {
let third = "jump"
print ("\(first) \(second) \(third)")
}
else {
print("huh?")
}
}
else {
print("huh?")
}
}
else if dict.keys.contains("second") {
if let second = dict["second"] as? String {
let third = second
let first = "first"
print ("\(first) \(second) \(third)")
}
}
else if dict.keys.contains("third") {
if let third = dict["third"] as? String{
print("I give up!")
}
}
}
}
Good Lord! What a nightmare!
I know, right?!
The if let pattern let me get away with all sorts of horrors (giving everything the same name is my favorite)!
Guard can help that code?
Only the delete key can fix that code! But guard can help!
func DoSomething(dictionary:[String : Any]?) {
guard let dict = dictionary
else { return }
if dict.keys.contains("first") {
guard let first = dict["first"] as? String,
first == "frog"
else {
print("huh?")
return
}
let second = "legs"
let third = "jump"
print ("\(first) \(second) \(third)")
}
else if dict.keys.contains("second") {
guard let second = dict["second"] as? String
else { return }
let third = second
let first = "first"
print ("\(first) \(second) \(third)")
}
else if dict.keys.contains("third") {
guard let third = dict["third"] as? String
else { return }
print("I give up!")
}
}
Wow! That code still sucks!
Yeah, but figuring out what the code does is WAAAAAAY easier.
The most important thing is the very first line of the function. If the dictionary is nil then the function doesn't do anything. Look at the first example and see how hard it is to figure out the same information.
I guess so
Look, guard isn't a silver bullet. But it does force you to write your code a little bit better. And better code is better! So use it!
Learn about if and if let over here