作者:Erica Sadun,原文連結,原文日期:2016-03-15
譯者:walkingway;校對:Cee;定稿:shanks
布萊恩·盧比的提問:“在 Swift 2 中你如何看待
guard case
文法和
~=
表達式?” 讓我來說的話,guard cases 真的适合帶相關值的模式比對嗎?就像下面這樣:
enum Test {case a(Int), b(String)}
let x = Test.a(2)
let y = Test.b("Hello")
guard case Test.a(let value) = x else {
fatalError("shouldn't fire")
}
guard case Test.b(let value) = x else {
fatalError("will fire")
}
答案是否定的,布萊恩所談論的是
guard case indices = index else { return nil }
,它的用法如下:
let foo = "abcdef".characters
let bar = "abcdefghij".characters
guard case foo.indices = foo.startIndex else {fatalError("won't fail")}
guard case foo.indices = bar.endIndex.predecessor() else {fatalError("fails")}
在模式比對中使用
guard case
來比較左右兩邊的值看上去很怪異,而使用
~=
就自然得多:
guard indices ~= index else { return nil }
我針對
guard case
認真地思考了一會:
- 恩,這很酷;
- 但我一點也不喜歡它。
guard case
的可讀性很糟糕。而且我不認為大部分的 Swift 開發者都知道或使用
guard case
進行比對。在原則“一段代碼被閱讀的次數要遠遠超過編寫的次數”(更不要提“最小驚訝原則”)的指導下,我會堅持使用操作符進行模式比對,而不是
guard case
。
不管你同意與否,都歡迎通過留言、推特、電子郵件的形式與我聯系。并且謝謝布萊恩,我喜歡研究這樣的問題。
Zachary Waldowski 在
上說:“if/guard/for/while case 是内建的模式,而 ~= 本質上是一種實作細節 :/”。也許是這樣,但我不認為這樣就能寫出漂亮的代碼,或讓代碼變得更容易閱讀。他最後回複到:“老實說,我無法明确給你一個答案;我覺得
if case
可讀性更好,但同僚卻認為我瘋了。”
本文由 SwiftGG 翻譯組翻譯,已經獲得作者翻譯授權,最新文章請通路 http://swift.gg。