快速,可选展开,如果条件可逆

vbe*_*nar 5 error-handling optional swift

假设我有返回可选的函数.如果成功则错误和价值为零:

func foo() -> Bar? { ... }
Run Code Online (Sandbox Code Playgroud)

我可以使用以下代码来使用此函数:

let fooResultOpt = foo()
if let fooResult = fooResultOpt {
    // continue correct operations here
} else {
    // handle error
}
Run Code Online (Sandbox Code Playgroud)

但是,对于任何非平凡的代码,此方法几乎没有问题:

  1. 最后执行错误处理,很容易错过一些东西.当错误处理代码跟随函数调用时,它会好得多.

  2. 正确的操作代码缩进一级.如果我们有另一个函数要调用,我们必须再缩进一次.

使用C,通常可以写这样的东西:

Bar *fooResult = foo();
if (fooResult == null) {
    // handle error and return
}
// continue correct operations here
Run Code Online (Sandbox Code Playgroud)

我找到了两种方法来实现与Swift类似的代码风格,但我也不喜欢.

let fooResultOpt = foo()
if fooResult == nil {
    // handle error and return
}
// use fooResultOpt! from here
let fooResult = fooResultOpt! // or define another variable
Run Code Online (Sandbox Code Playgroud)

如果我写"!" 在任何地方,它只是看起来不好我的口味.我可以引入另一个变量,但这看起来也不好看.理想情况下,我希望看到以下内容:

if !let fooResult = foo() {
    // handle error and return
}
// fooResult has Bar type and can be used in the top level
Run Code Online (Sandbox Code Playgroud)

我是否错过了规范中的某些内容,或者是否有其他方法可以编写好看的Swift代码?

ric*_*ter 2

你的假设是正确的\xe2\x80\x94Swift 中没有“否定 if-let”语法。

\n\n

我怀疑原因之一可能是语法完整性。在整个 Swift(以及其他受 C 语言启发的语言中)中,如果您有一个可以绑定局部符号(即命名新变量并赋予它们值)并且可以具有块体(例如 if、while、for)的语句,那么这些语句绑定的范围仅限于所述块。相反,让块语句将符号绑定到其封闭范围将是不一致的。

\n\n

尽管 \xe2\x80\x94 我建议提交一个错误并看看 Apple 对此做了什么,但这仍然是一个值得考虑的合理的事情。

\n