【问题标题】:My first guard, is it appropriate here?我的第一个守卫,这里合适吗?
【发布时间】:2015-09-09 15:48:04
【问题描述】:

我正在使用 Swift 2,我正在查看我的代码以查找我正在保护的实例,并且我可能想要使用 guard。这是一个...

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 = ""
}

此代码的目标是将文本文件的内容读入mods。这个文件可能存在也可能不存在,所以我想在尝试读取内容之前测试它是否存在。

这是使用guard 的合适地方吗?它似乎只有else 语法,而不是then 侧,所以你不能直接匹配这个语法。我可以在开始时将 mods 设置为 "" 然后保护读取,但我不清楚这是否真的提高了可读性?

附带说明一下,我发现 String(contentsOfFile) 抛出的异常很奇怪,而 bundle.pathForResource() 只返回一个 nil。我更喜欢后者。

【问题讨论】:

    标签: swift2 guard-statement


    【解决方案1】:

    在这种情况下,我建议使用三元运算符:

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

    另一方面,在这种情况下,您甚至不能使用 guard,因为 else 块必须使用 returnbreakcontinuethrow 退出作用域

    【讨论】:

    • 对,这就是我问的原因。从理论上讲,守卫似乎是您想要使用的东西,但是投掷意味着它不起作用。很奇怪……
    • 你说的“抛出意味着它不起作用”是什么意思?
    【解决方案2】:

    在这种情况下,您可以在这里像这样使用“守卫”:

    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 ()
    {
    
    }
    

    【讨论】:

      【解决方案3】:

      在这里,我使用 Guard 修改了您的代码,如下所示。它减少了代码行,我们的意图也很清楚。检查此代码

      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)
      

      在这里您定义了从 ErrorType 协议扩展而来的枚举(错误处理程序)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-11
        • 2011-01-17
        • 2011-03-30
        • 1970-01-01
        • 2021-06-03
        • 2016-09-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多