不久前在使用 guard 的時候,因為忘記加上 return,發生了常見的低級錯誤:
什麼!guard 一定要 return 喔,不能直接跳轉就好?
查看到彼得潘大大的討論文:
else { } 的程式執行後,必須離開 guard 所在區塊,如此才不會繼續往下執行條件成立時要做的事。就像剛剛的例子,我們利用 return 離開 function motherSay。
奇怪,那怎麼不設計成 guard 的 else 中預設最後面就會自動 return,不需要 explicitly 寫出 return?
我想說查看一下 swift-evolution 有沒有關於這個設計理念的說明,果然被我找到了。
- infer
return
for omittedguard
body
It has been proposed many times to allow omission of the
guard
body for the sake of brevity.
而官方的說明是:
However, a core principle of Swift is to make control flow explicit and visible. ….. Implicit returns would violate this principle
我的解讀是之所以不採用 infer 的方式忽略掉 return,應該是因為要遵從 swift 的設計理念,讓程式碼好讀懂。
另外還有一個我也有想過的項目:
- rename
gaurd
tounless
It is a common request that
guard
be renamedunless
….People requesting this change argue thatguard
is simply a logically invertedif
statement, and thereforeunless
is a more obvious keyword.
不適合的理由:
However, such requests stem from a fundamental misunderstanding of the functionality provided by
guard
. Unlikeif
,guard
enforces that the code within its curly braces provides an early exit from the codepath.
意思大概是說,雖然 unless 在邏輯上是 if 的反義詞,但是通常語意上 unless COND (then) { …} 這樣是「希望要做後面 then 的部分,除非 COND 成立」
而 guard COND else { … },語意上是:「有 COND 嗎?沒有,你給我離開」(就像警衛攔查可疑人物一樣),是一個希望提早排除(early exit) 的概念。
以上如果有解讀錯誤的地方,歡迎留言給我~