I'm playing with Swift 2 and I'm looking through my code for instances where I'm guarding and I might want to use guard. Here's one...
var mods : String = ""
let modpath = NSBundle.mainBundle().pathForResource(filename, ofType: "ini", inDirectory: "mods/gamedata")
if modpath?.length > 0 {
mods = try! String(contentsOfFile: modpath!, encoding: NSUTF8StringEncoding)
} else {
mods = ""
}
The goal of this code is to read the contents of a text file into mods. This file may or may not exist, so I want to test whether it does before I try to read the contents.
Is this an appropriate place to use guard? It appears it only has the else syntax, not the then side, so you can't directly match this syntax. I could set mods to "" at the start and then guard the read, but it's not clear to me this really improves the readability?
As a side note, I find it very weird that String(contentsOfFile) throws, while bundle.pathForResource() simply returns a nil. I prefer the later.
In this Situation I would suggest to use the ternary operator:
On the other hand you can't even use guard in this case because the else block has to quit the scope with
return,break,continueorthrow