为什么需要避免在 Swift 中使用 C 风格的 /*... */ 注释?

Why the need to avoid C-style /*... */ comments in Swift?

我阅读了 this Swift 风格指南,它显然是基于 Apple 自己的 Swift 库风格:

'Non-documentation comments always use the double-slash format (//), never the C-style block format (/* ... */).'

为什么不对多行使用 C 风格注释很重要?

虽然我没有具体的答案,但我倾向于建议双斜线格式(//)

我认为 Swift 风格指南是这样说的,因为他们也将它用作默认设置。

这是什么意思?例如,如果您突出显示多行并按 (cmd+/),它将 comment/uncomment 所有突出显示的行。

注意:只有在双斜杠格式(//)中才会取消注释突出显示的行

我认为单行注释 (//) 比多行注释 (/* */ 有一些好处,称这些 "C-style" 没有意义,因为这两种样式在 C 中都有效)更容易切换。

  1. 单行注释更容易 insert/remove,因为大多数 IDE 都有切换它们的快捷方式。在Xcode中,默认为 + /
  2. 多行注释引入了更多不一致的机会。应该使用哪一个?

    • 这种方法很简洁,但是打乱了A的水平对齐

      /* A 
      B
      C */
      
    • 这种方法保持元素的对齐不变,但浪费了垂直space:

      /*
      A
      B
      C
      */
      
    • 这种方法保持元素的对齐完整,并且不会占用太多额外的垂直空间space

      /*
      A
      B
      C */
      
    • 这是两全其美,我不推荐。

      /* A
      B
      C
      */
      
    • 这在各方面都更好。对齐是完整的。没有多余的水平 space 被浪费。

      // A
      // B
      // C
      
  3. 使用单行注释更容易更改注释部分。比较:

    • 使用单行注释,只需删除相关位置的前导 // 即可 之前:

      // A
      // B
      // C
      

      之后:

      // A
      // B
      C // Just had to remove the leading "//" here
      
    • 如果是多行注释,需要在末尾"cut" */,在新的末尾粘贴。两个动作。

      之前:

      /*
      A
      B
      C
      */
      

      之后:

      /*
      A
      B
      */ // 1. had to insert "*/" here
      C // 2. had to remove "*/" from the end
      
  4. 这在 Swift 中不是问题,但在 C 中,多行注释不可嵌套。假设您有一个函数,其中包含多行注释。但是您想暂时注释掉该功能(无论出于何种原因,仅作为示例)。如果两个注释都是多行的,则无法编译。此代码无效:

    /*        // This "/*" is treated as the start of a comment block
    /*        // This "/*" is commented, thus ignored.
    */        // This "*/" is treated as the end of the comment block
    */        // This "*/" tries to close the comment block, but it's not in a comment block. This is invalid.
    

    但是Swift没有这个问题。我想解析器有一个它跟踪的内部 "comment block nesting level" 。每个 /* 递增它,每个 */ 递减它。只有当 "comment block nesting level" 回到 0.

  5. 后,评论区才会关闭

不是没用

然而,这并不意味着多行注释在 Swift 中没有用处。当我玩弄一行的子表达式时,我经常使用它们。例如,如果我有这个函数调用:

someFunction(someValue + 1, someOtherParam)

我可以看到一个函数在没有 + 1 的情况下使用块注释的行为:

someFunction(someValue /* + 1 */, someOtherParam)

仅使用单行注释实现同样的事情需要我做类似的事情:

someFunction(someValue // + 1
        , someOtherParam)

或者引入临时局部变量:

let incrementedValue = someValue // + 1
someFunction(incrementedValue, someOtherParam)

两者都不是很好。