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中的递增(++)和递减(--)被取消的原因-官方答复》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

大连接

大连接

[美] 尼古拉斯•克里斯塔基斯(Nicholas A. Christakis)、[美] 詹姆斯•富勒(James H. Fowler) / 简学 / 中国人民大学出版社 / 2013-1 / 59.90元

[内容简介] 1. 本书是继《六度分隔》之后,社会科学领域最重要的作品。作者发现:相距三度之内是强连接,强连接可以引发行为;相聚超过三度是弱连接,弱连接只能传递信息。 2. 本书讲述了社会网络是如何形成的以及对人类现实行为的影响,如对人类的情绪、亲密关系、健康、经济的运行和政治的影响等,并特别指出,三度影响力(即朋友的朋友的朋友也能影响到你)是社会化网络的强连接原则,决定着社会化网络的......一起来看看 《大连接》 这本书的介绍吧!

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

在线压缩/解压 JS 代码

在线进制转换器
在线进制转换器

各进制数互转换器

随机密码生成器
随机密码生成器

多种字符组合密码