iOS-Swift中的遞增(++)和遞減(--)被取消的原因-官方答覆

Lebus發表於2019-04-30

眾所周知,在很多程式語言中,對一個變數遞增1用++,遞減1用--,在Swift3之前也是可以這麼用的,但之後被取消了。

所以在目前Swift5的版本中,只能用+=1-=1來進行遞增和遞減了

如果堅持用++--將會提示以下錯誤:

Use of unresolved operator '++'; did you mean '+= 1'?

Use of unresolved operator '--'; did you mean '-= 1'?

也是好奇為毛Swift把這麼好用的語法取消了,之前也有老外諮詢過Chris Lattner(Swift語言締造者),並獲得了回覆。 最近也是被學生問起這個問題,所以拿出來分享一下,以下是我總結的:

  1. 這是Swift的新功能(我就這麼弄,怎麼了)
  2. ++也並沒比 += 1簡潔多少
  3. 別把Swift和別的語言混淆在一起(這,就是個性)
  4. 別的語言的++主要是用在for迴圈中:for i = 0; i < n; i++ { ... },但Swift語言的for迴圈可以這麼寫:for i in 0..<n { ... },所以++就沒什麼用了
  5. ++讀起來不太擬人,感覺沒什麼意義,不符合Swift語言一貫的超長命名方式,比如x - ++xfoo(++x, x++),沒註釋的話之後連自己都看不懂。
  6. 作者本人不喜歡++--

一句話:我們不一樣!

以下是Chris Lattner答覆的原文:

1.These operators increase the burden to learn Swift as a first programming language - or any other case where you don't already know these operators from a different language.

2.Their expressive advantage is minimal - x++ is not much shorter than x += 1.

3.Swift already deviates from C in that the =, += and other assignment-like operations returns Void (for a number of reasons). These operators are inconsistent with that model.

4.Swift has powerful features that eliminate many of the common reasons you'd use ++i in a C-style for loop in other languages, so these are relatively infrequently used in well-written Swift code. These features include the for-in loop, ranges, enumerate, map, etc.

5.Code that actually uses the result value of these operators is often confusing and subtle to a reader/maintainer of code. They encourage "overly tricky" code which may be cute, but difficult to understand.

6.While Swift has well defined order of evaluation, any code that depended on it (like foo(++a, a++)) would be undesirable even if it was well-defined.

7.These operators are applicable to relatively few types: integer and floating point scalars, and iterator-like concepts. They do not apply to complex numbers, matrices, etc.

Finally, these fail the metric of "if we didn't already have these, would we add them to Swift 3?"

廣告時間:小弟的iOS12零基礎視訊教程(每章皆可試聽):

m.study.163.com/provider/48…

相關文章