apple/swift-evolution 上關於 guard 的有趣討論

else { } 的程式執行後,必須離開 guard 所在區塊,如此才不會繼續往下執行條件成立時要做的事。就像剛剛的例子,我們利用 return 離開 function motherSay。

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

It is a common request that guard be renamed unless….People requesting this change argue that guard is simply a logically inverted if statement, and therefore unless is a more obvious keyword.

However, such requests stem from a fundamental misunderstanding of the functionality provided by guard. Unlike if, guard enforces that the code within its curly braces provides an early exit from the codepath.

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store