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

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

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

查看所有标签

猜你喜欢:

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

运营制胜

运营制胜

张恒 / 电子工业出版社 / 2016-10-1 / 65

《运营制胜——从零系统学运营构建用户增长引擎》主要从内容运营、用户运营、推广运营三个方向来介绍产品运营方面的知识。 其中内容运营主要介绍了内容生成的机制、内容方向设定、内容输出、内容生产引擎、内容推荐机制、数据如何驱动内容运营、内容运营的KPI 设定、建立内容库、内容的赢利模式。用户运营主要介绍了产品的冷启动、获得种子用户及早期用户、建立用户增长引擎、利用心理学引爆产品用户增长、增加用户活跃......一起来看看 《运营制胜》 这本书的介绍吧!

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

在线压缩/解压 CSS 代码

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

多种字符组合密码

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码