My first guard, is it appropriate here?

125 Views Asked by At

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.

3

There are 3 best solutions below

2
On

In this Situation I would suggest to use the ternary operator:

let modpath = NSBundle.mainBundle().pathForResource(filename, ofType: "ini", inDirectory: "mods/gamedata")
let mods = modpath?.length > 0  ? try! String(contentsOfFile: modpath!, encoding: NSUTF8StringEncoding) : ""

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, continue or throw

0
On

You can use 'guard' like this here, in this case:

var mods : String = ""
guard let modpath = NSBundle.mainBundle().pathForResource(filename, ofType: "ini", inDirectory: "mods/gamedata") else {
    mods = ""
}
do
{
    mods = try String(contentsOfFile: modpath!, encoding: NSUTF8StringEncoding)
} 
catch ()
{

}
0
On

Here, Using Guard i have modified your code like below. it reduces lines of code and our intension is clear too. check this code

var mods : String = ""

let modpath = NSBundle.mainBundle().pathForResource(filename, ofType: "ini", inDirectory: "mods/gamedata")

 guard modpath?.length > 0 else { throw ErrorHandler.errorMessage }

mods = try! String(contentsOfFile: modpath!, encoding: NSUTF8StringEncoding)

Here you have define enum (error handler) that was extending from ErrorType protocol.