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



下面抛出一个错误。

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

是的,这在if-let中是可能的(这里有更多关于iflet的信息(:

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(这里有更多关于guard-let的信息(:

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

CCD_ 6在函数中特别有用。如果您的条件不满足,您可以退出该功能。否则,您定义的let/var变量在函数中可用。

最新更新