Swift 2 introduced the guard
keyword, a handy bit of syntactic sugar with semantics similar to a debugging assert
. It’s pure sugar, nothing more than an alternate if
construction, but I’ve found that liberal use of guard has made my code far more readable with very little effort.
1
2
3
4
5
6
7
8
9
|
func checkAuthenticated(authenticated: Bool) -> Bool {
guard authenticated else {
// Do something in response to failure
return false
}
return true
}
|
Basically, guard
is a sort of inverse if
. You could just as easily write the (hilariously contrived) above example as:
1
2
3
4
5
6
7
8
9
|
func checkAuthenticated(authenticated: Bool) -> Bool {
if !authenticated {
// Do something in response to failure
return false
}
return true
}
|
I strongly prefer the guard
version, though, as I find the guard...else
line to be much more explicit than the narrow and easily-overlooked !
. guard
really comes into its own, however, when dealing with optionals. I often find that I end up with a lot of code like:
1
2
3
4
5
6
7
8
9
10
|
func updateGameCenterDisplay(username: String?) {
if let user = username {
// Do something sensible with ‘user’.
usernameLabel.text = user
return
}
// username is nil, prompt for login.
}
|
This is fine, but it feels like inverted logic. I’d far rather take care of the error cases up front, and guard
lets me do just that:
1
2
3
4
5
6
7
8
9
|
func updateGameCenterDisplay(username: String?) {
guard let user = username else {
// username is nil, prompt for login.
return
}
// Do something sensible with ‘user’.
usernameLabel.text = user
}
|
Leave a Reply