Swift 2: Improving guards
One of the many exciting announcements at WWDC for the new version of Swift were guards. They make it less cumbersome to check for Optional types, and keeps your code more concise.
Guards lets you turn this
func search(string: String?) -> Int? {
var result: Int? if let match = self.indexOf(string) {
result = match
} return result
}
Into this
func search(string: String?) -> Int? {
guard let match = self.indexOf(string) else {
return nil
} return match
}
That saves a bit of keystrokes and a lot of headaches — especially with more than just a couple of Optionals.
However, I noted quite quickly an unnecessary part of guards, which would otherwise have made it even more concise and trivial.
Get Christian Petersen’s stories in your inbox
Join Medium for free to get updates from this writer.
Specifically the part of explicitly returning nil. It is well-known fact that Optionals can hold either a value or nil, so when the return type of a function conforms to an Optional it would make much sense that a guard clause should return nil by default.
guard let match = self.indexOf(string)
return matchThis saves a great amount of characters, and also makes your a lot cleaner — a few of those wouldn’t hurt as much.
But what about functions, that does return Optionals? Take this example
func getRange(s: String) -> Int {
guard let range = self.rangeOfString(s)
where range.count > 0 else {
return 0
} return range.count
}
Here we could get rid of the brackets
guard let range = self.rangeOfString(s)
where range.count > 0 else return 0Not a huge change, but enough to make it worth it — and a bit more verbal too.
While we are at this topic, there’s a lot of improvements I’d like to see in Swift to save a few keystrokes and still keep the code readable and coherent. This would definitely make it a lot more fun to write Swift code, without having to move your hands in weird positions for trivial operations like this.
What do you think about this? Would it benefit you, or don’t you mind the extra keystrokes? I’d love to hear your thoughts.





![[HTB Sherlock] Baggage](https://miro.medium.com/v2/resize:fit:1358/format:webp/1*2oD2jUMt5vfA_KvDpbAi5w.png)