衆所周知,在不少編程語言中,對一個變量遞增1用++
,遞減1用--
,在Swift3以前也是能夠這麼用的,但以後被取消了。express
+=1
和-=1
來進行遞增和遞減了若是堅持用++
或--
將會提示如下錯誤:編程
也是好奇爲毛Swift把這麼好用的語法取消了,以前也有老外諮詢過Chris Lattner(Swift語言締造者),並得到了回覆。 最近也是被學生問起這個問題,因此拿出來分享一下,如下是我總結的:app
++
也並沒比 += 1
簡潔多少++
主要是用在for循環中:for i = 0; i < n; i++ { ... }
,但Swift語言的for循環能夠這麼寫:for i in 0..<n { ... }
,因此++
就沒什麼用了++
讀起來不太擬人,感受沒什麼意義,不符合Swift語言一向的超長命名方式,好比x - ++x
或 foo(++x, x++)
,沒註釋的話以後連本身都看不懂。++
和--
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.ide
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.oop
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.lua
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.scala
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.code
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?"