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)
但是,对于任何非平凡的代码,此方法几乎没有问题:
最后执行错误处理,很容易错过一些东西.当错误处理代码跟随函数调用时,它会好得多.
正确的操作代码缩进一级.如果我们有另一个函数要调用,我们必须再缩进一次.
使用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代码?
| 归档时间: |
|
| 查看次数: |
946 次 |
| 最近记录: |