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

栏目: Swift · 发布时间: 6年前

内容简介:众所周知,在很多编程语言中,对一个变量递增1用如果坚持用也是好奇为毛Swift把这么好用的语法取消了,之前也有老外咨询过

众所周知,在很多编程语言中,对一个变量递增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?"


以上所述就是小编给大家介绍的《iOS-Swift中的递增(++)和递减(--)被取消的原因-官方答复》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

软件开发者路线图

软件开发者路线图

Dave H. Hoover、Adewale Oshineye / 王江平 / 机械工业出版社 / 2010年9月 / 35.00元

作为一名软件开发者,你在奋力推进自己的职业生涯吗?面对今天日新月异和不断拓展的技术,取得成功需要的不仅仅是技术专长。为了增强专业性,你还需要一些软技能以及高效的学习技能。本书的全部内容都是关于如何修炼这些技能的。两位作者Dave Hoover和Adewale Oshineye给出了数十种行为模式,来帮你提高主要的技能。 本书中的模式凝结了多年的调查研究、无数次的访谈以及来自O’Reilly在......一起来看看 《软件开发者路线图》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码