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

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

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

查看所有标签

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

CSS权威指南(第三版·英文影印版)

CSS权威指南(第三版·英文影印版)

[美] Eric A.Meyer / 东南大学出版社 / 2007-06 / 68.00元

著名的CSS专家Eric A.Meyer他招牌式的智慧和无与伦比的经验引领读者探索了CSS的各个部 分,包括属性、标记、特性和实现。此外,他还就现实应用中的一些问题,例如浏览器的支持和设计方针,发表了看法。你所要知道的就是HTML 4.0的知识,这样就可以创建整洁、易于维护的脚本,以与桌面出版系统同样的优雅和控制能力管理网站布局和分页。你将会学到: 精妙地设计文本风格 用户界面、......一起来看看 《CSS权威指南(第三版·英文影印版)》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具