反轉假設我有返回可選的函數。零如果錯誤和值,如果成功:swift,可選展開,如果條件
func foo() -> Bar? { ... }
我可以使用下面的代碼使用此功能工作:
let fooResultOpt = foo()
if let fooResult = fooResultOpt {
// continue correct operations here
} else {
// handle error
}
但是也有一些問題這種方法對於任何非平凡代碼:
錯誤處理在最後執行,很容易錯過任何東西。當錯誤處理代碼遵循函數調用時,它會好得多。
正確的操作代碼縮進一級。如果我們有另一個函數可以調用,我們必須再縮進一次。
用C人們通常會寫這樣的事情:
Bar *fooResult = foo();
if (fooResult == null) {
// handle error and return
}
// continue correct operations here
我發現了兩種方式來實現類似的代碼風格的雨燕,但我也不喜歡。
let fooResultOpt = foo()
if fooResult == nil {
// handle error and return
}
// use fooResultOpt! from here
let fooResult = fooResultOpt! // or define another variable
如果我會寫「!」到處都是,我的口味看起來很糟糕。我可以引入另一個變量,但這看起來不太好。理想情況下,我想看到以下內容:
if !let fooResult = foo() {
// handle error and return
}
// fooResult has Bar type and can be used in the top level
我錯過了什麼,在說明書或有一些其他的方式來寫好看SWIFT代碼?
謝謝,但你的解決方案不從語法不同,如果(讓值= X){。 ..}其他{...}並具有我在問題中提到的所有缺點。 – vbezhenar 2014-10-13 09:19:46