iOS-Swift中的递增(++)和递减(--)被取消的缘由-官方答复

众所周知,在不少编程语言中,对一个变量递增1用++,递减1用--,在Swift3以前也是能够这么用的,但以后被取消了。express

因此在目前Swift5的版本中,只能用+=1-=1来进行递增和递减了

若是坚持用++--将会提示如下错误:编程

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

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

也是好奇为毛Swift把这么好用的语法取消了,以前也有老外咨询过Chris Lattner(Swift语言缔造者),并得到了回复。 最近也是被学生问起这个问题,因此拿出来分享一下,如下是我总结的:app

  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.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?"

广告时间:小弟的iOS12零基础视频教程(每章皆可试听):

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

相关文章
相关标签/搜索