代码之家  ›  专栏  ›  技术社区  ›  sunknudsen

在Swift中是否可以在同一行上进行布尔比较和变量赋值?

  •  0
  • sunknudsen  · 技术社区  · 4 年前

    if (
      CommandLine.arguments[1].range(of: ".json$", options: .regularExpression, range: nil, locale: nil) != nil &&
      let _config = loadConfig(CommandLine.arguments[1])
    ) {
      self.config = _config
    } else {
      showAlert("Invalid config file")
      terminate()
    }
    
    0 回复  |  直到 4 年前
        1
  •  3
  •   Jeroen    4 年前

    是的,这在 if-let ( here 更多信息请告知):

    if
        let _ = CommandLine.arguments[1].range(of: ".json$", options: .regularExpression, range: nil, locale: nil),
        let _config = loadConfig(CommandLine.arguments[1])
    {
        self.config = _config
    }
    else
    {
        showAlert("Invalid config file")
        terminate()
    }
    

    所以这里与代码的区别是 && 替换为 , (和支架 ( ... )

    也可以使用 guard-let ( here 关于守卫的更多信息请:

    guard
        let _ = CommandLine.arguments[1].range(of: ".json$", options: .regularExpression, range: nil, locale: nil),
        let _config = loadConfig(CommandLine.arguments[1])
    else
    {
        showAlert("Invalid config file")
        terminate()
        
        return // Return is needed in guard-let.
    }
    
    self.config = _config
    

    在函数中特别有用。如果不满足您的条件,您可以退出函数。否则,你的定义 let / var