Swift是否支持生成文档的功能?

254
许多编程语言支持文档注释,通过解析相同的代码允许生成器(如javadocdoxygen)生成代码文档。

Swift是否具有类似的类型文档注释功能?


知道Xcode和Objective-C允许文档注释,我相信苹果公司将在不久的将来为Xcode和Swift添加此选项(但这只是一种假设,我没有证据)。 - Garoal
@Δ开发者 我也是这么想的,但由于我没有看到任何参考资料,所以我想知道是否有人可以确认,并且是否会有任何特定的文档工具。 - pconcepcion
1
他们肯定会在未来添加一些东西,// MARK: 注释也计划在未来的 Xcode 版本中推出。 - Leandros
Doxygen风格的注释对于类方法来说有一些限制,但是我个人会继续使用Doxygen风格(就像我在Obj-C中所做的那样),并希望Xcode能够改进对它们的支持。 - Pascal
1
有关文档块参数,请参见https://dev59.com/ZpPfa4cB1Zd3GeqPBEmQ#41970146。 - Leonard Pauli
13个回答

413

文档注释在Xcode中有原生支持,可以生成智能渲染的文档,包括快速帮助(当使用-点击符号时,在弹出窗口中)和快速帮助检查器 ⌥⌘2 中的文档。

符号文档注释现在基于与丰富的playground注释相同的Markdown语法,因此现在可以直接在源代码文档中使用playgrounds中的大部分功能。

有关语法的完整详细信息,请参见标记格式参考。请注意,丰富的playground注释和符号文档的语法存在一些差异;这些差异在文档中指出(例如,块引用只能在playgrounds中使用)。

下面是一个示例和目前适用于符号文档注释的语法元素列表。


更新

Xcode 7 beta 4 ~ 添加了"- Throws: ..."作为顶级列表项,与参数和返回描述一起显示在快速帮助中。

Xcode 7 beta 1 ~ Swift 2的语法发生了一些重大变化 - 文档注释现在基于Markdown(与playgrounds相同)。

Xcode 6.3(6D570)~ 缩进文本现在被格式化为代码块,并嵌套后续缩进。在这样的代码块中不可能留下空行 - 尝试这样做会导致文本被附加到最后一行上,其中包含任何字符。

Xcode 6.3 beta ~ 现在可以使用反引号将内联代码添加到文档注释中。


Swift 2示例

/// Text like this appears in "Description".
///
/// Leave a blank line to separate further text into paragraphs.
///
/// You can use bulleted lists (use `-`, `+` or `*`):
///
/// - Text can be _emphasised_
/// - Or **strong**
///
/// Or numbered lists:
///
/// 7. The numbers you use make no difference
/// 0. The list will still be ordered, starting from 1
/// 5. But be sensible and just use 1, 2, 3 etc…
///
/// ---
///
/// More Stuff
/// ==========
///
/// Code
/// ----
///
/// Use backticks for inline `code()`. Indentations of 4 spaces or more will create a code block, handy for example usage:
///
///     // Create an integer, and do nothing with it
///     let myInt = 42
///     doNothing(myInt)
///
///     // Also notice that code blocks scroll horizontally instead of wrapping.
///
/// Links & Images
/// --------------
///
/// Include [links](https://en.wikipedia.org/wiki/Hyperlink), and even images:
///
/// ![Swift Logo](/Users/Stuart/Downloads/swift.png "The logo for the Swift programming language")
///
/// - note: That "Note:" is written in bold.
/// - requires: A basic understanding of Markdown.
/// - seealso: `Error`, for a description of the errors that can be thrown.
///
/// - parameters:
///   - int: A pointless `Int` parameter.
///   - bool: This `Bool` isn't used, but its default value is `false` anyway…
/// - throws: A `BadLuck` error, if you're unlucky.
/// - returns: Nothing useful.
func doNothing(int: Int, bool: Bool = false) throws -> String {
    if unlucky { throw Error.BadLuck }
    return "Totally contrived."
}

Swift Documentation Quick Help


Swift 2的语法(基于Markdown)


注释样式

支持使用///(内联)和/** */(块)样式的注释来生成文档注释。虽然我个人更喜欢/** */注释的视觉样式,但是在复制/粘贴时,Xcode的自动缩进可能会破坏此注释样式的格式,因为它会删除前导空格。例如:

/**
See sample usage:

    let x = method(blah)
*/

当粘贴时,代码块缩进会被删除,并且不再呈现为代码:
/**
See sample usage:

let x = method(blah)
*/

因此,我通常使用///,并将在本答案的其余示例中使用它。


块级元素

标题:

/// # My Heading

或者
/// My Heading
/// ==========


副标题:

/// ## My Subheading

或者

/// My Subheading
/// -------------


水平分隔线:

/// ---

无序列表(用符号标记):
/// - An item
/// - Another item

你也可以使用+*来创建无序列表,只需要保持一致即可。 有序(编号)列表:
/// 1. Item 1
/// 2. Item 2
/// 3. Item 3


Code blocks:

///    for item in array {
///        print(item)
///    }

至少需要四个空格的缩进。


内联元素

强调(斜体):

/// Add like *this*, or like _this_.


强调(粗体):

/// You can **really** make text __strong__.

请注意,您不能在同一元素上混合使用星号(*)和下划线(_)。 行内代码:
/// Call `exampleMethod(_:)` to demonstrate inline code.


链接:

/// [Link Text](https://en.wikipedia.org/wiki/Hyperlink)


图片:

/// ![Alt Text](http://www.example.com/alt-image.jpg)

URL 可以是网络 URL(使用 "http://")或绝对文件路径 URL(似乎无法使用相对文件路径)。
链接和图片的 URL 也可以与内联元素分开,以便将所有 URL 放在一个可管理的位置:
/// A [link][1] an an ![image][2]
///
/// ...
///
/// [1]: http://www.example.com
/// [2]: http://www.example.com/image.jpg


关键词

除了Markdown格式外,Xcode还识别其他标记关键词以在快速帮助中突出显示。这些标记关键词大多采用-<keyword>:的格式(例外是parameter,它还包括冒号前的参数名称),其中关键词本身可以写成任何大小写字母的组合。

符号部分关键词

以下关键词以突出的形式显示在帮助查看器中,位于“描述”部分下方,“声明于”部分上方。当包含这些关键词时,它们的顺序固定为如下所示,即使您可以按任何顺序在注释中包含它们。

请参阅标记格式参考中的符号部分命令章节,获取完整记录的关键词列表及其预期用途。

/// - parameters:
///   - <#parameter name#>:
///   - <#parameter name#>:
/// - throws:
/// - returns:

或者,您可以这样编写每个参数:

/// - parameter <#parameter name#>:

符号描述字段关键词

以下关键词列表以粗体标题形式显示在帮助查看器的“描述”部分的正文中。它们将按照您编写它们的顺序出现,就像“描述”部分的其余内容一样。

完整列表由Erica Sadun的这篇优秀博客文章改写而来。还可以查看标记格式参考中的符号描述字段命令部分中关键词及其预期用途的完全记录列表。

归属:

/// - author:
/// - authors:
/// - copyright:
/// - date:

可用性:

/// - since:
/// - version:

警告:

/// - attention:
/// - important:
/// - note:
/// - remark:
/// - warning:

开发状态:

/// - bug:
/// - todo:
/// - experiment:

实现品质:

/// - complexity:

功能语义:

/// - precondition:
/// - postcondition:
/// - requires:
/// - invariant:

交叉引用:
/// - seealso:

导出文档

可以使用开源命令行工具Jazzy从内联文档生成HTML文档(旨在模仿苹果的官方文档)。

$ [sudo] gem install jazzy
$ jazzy
Running xcodebuild
Parsing ...
building site
jam out ♪♫ to your fresh new docs in `docs`

控制台示例取自this NSHipster article


1
看起来Xcode 6.3(6D570)的最终版本行为已经改变了。缩进块现在被格式化为代码块,并且可以嵌套超过两个级别。 - NexD.
2
非常好的Swift 2.0文档语法描述。您应该更新帖子以包括/// - todo: keyword关键字。 - leonardo
2
@uchuugaka 实际上不是这样的。它以前可能基于reStructuredText,但从Xcode 7开始,文档注释基于Markdown,并具有与playground注释相同的基本格式。有关详细信息,请参见Xcode 7发布说明 - Stuart
2
有没有办法链接到同一文件中的其他函数,就像JavaDoc那样?例如,“请参阅myOtherMethod(param1 :)以获取扩展功能”。 - Ky -
3
是的,可以通过使用 /// - Tag: otherMethod[otherMethod](x-source-tag://otherMethod) 来实现。有关更多详细信息,请参见 我的答案 - Clay Ellis
显示剩余7条评论

58

以下是一些在Xcode 6中编写Swift代码时可用于文档化的方法。尽管存在一些错误和对冒号的敏感问题,但这比没有强。具体方法如下:

class Foo {

    /// This method does things.
    /// Here are the steps you should follow to use this method
    ///
    /// 1. Prepare your thing
    /// 2. Tell all your friends about the thing.
    /// 3. Call this method to do the thing.
    ///
    /// Here are some bullet points to remember
    ///
    /// * Do it right
    /// * Do it now
    /// * Don't run with scissors (unless it's tuesday)
    ///
    /// :param: name The name of the thing you want to do
    /// :returns: a message telling you we did the thing
    func doThing(name : String) -> String {
        return "Did the \(name) thing";
    }
}

上述内容在快速帮助中呈现时,会按照格式化的数字列表、项目符号、参数和返回值文档的方式呈现,这是你所期望的。
这些都没有被记录下来 - 提交一个Radar来帮助他们改进。

2
Mattt Thompson写了一篇文章,他认为这是reStructuredText - eonil
在上面的例子中,加号(+)和减号(-)符号也将作为项目符号,除了显示的星号。 - Vince O'Sullivan
似乎在任何解释性文本和“:param:”或“:returns:”行之间需要一个空白注释(///)行。省略此操作会导致XCode(在撰写本文时为6.1.1)将参数帮助包含在函数描述的主体中。 - Robin Macharg
不幸的是,这在Xcode 7 Beta上无法工作。希望他们能在发布版本中修复它。 - stevo.mit
1
Xcode 7采用了不同的语法:http://ericasadun.com/2015/06/14/swift-header-documentation-in-xcode-7/ - Zmey

42

Xcode 8 的新功能,您可以像这样选择一个方法

func foo(bar: Int) -> String { ... }

然后按下command + option + /或从Xcode的“编辑器”菜单中选择"结构" - "添加文档",它将为您生成以下注释模板:

/// <#Description#>
///
/// - parameter bar: <#bar description#>
///
/// - returns: <#return value description#>

1
谢谢您的回复。我想提醒一下,在丹麦键盘上,您所指示的快捷键似乎无法使用,因为“/”是Shift+“7”。 - RenniePet

27

Swift包含“///”注释处理(虽然可能还不是全部)。

写出类似于这样的东西:

/// Hey!
func bof(a: Int) {

}

然后选项点击函数名称,voilà :)


11

我可以确认ShakenManChild提供了正确的解决方案。

请确保在描述下方有一个空行!

一种无效的情况

正确的方式

另一种方式

另一种注释样式


8
在Xcode编辑器中,选择“结构”菜单,然后选择“添加文档”。

enter image description here


是的,这个问题在3个月前就被Logan Jahnke提出过了。 - Franklin Yu

8
是的。基础常见功能(我已经用Obj-C等效方式制作了代码片段) Objective-C:
/**
 @brief <#Short description - what it is doing#>

 @discussion <#Description#>

 @param  <#paramName#> <#Description#>.

 @return <#dataType#> <#Description#>.
 */

Swift

/**
<#Short inline description - what it is doing#>

<#Description#>

:param:  <#paramName#> <#Description#>.

:returns: <#dataType#> <#Description#>.
*/

7

3
VVDocumenter 和 Jazzy 一起使用也非常有用。 - Ross Gibson

6
我在Xcode二进制文件中发现了一些有趣的东西,它们以 .swiftdoc 结尾。这些文件明显包含文档,因为它们包含Swift UIKit / Foundation API的文档,但不幸的是,它似乎是一种专有文件格式,只能在Xcode的文档查看器中使用。

1

Swift 5.6+ 提供了丰富的 API 参考文档和交互式教程生成,使用 DocC ⇗Swift-DocC 插件 ⇗ 提供了 Swift Package Manager 的命令,支持为 SwiftPM 库和可执行文件构建文档。

Package.swift

    dependencies: [
        // other dependencies
        .package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"),
    ],

终端:

swift package generate-documentation
swift package plugin generate-documentation --help

资源

博客:Swift.org

文档:已存档

示例代码

WWDC会议


语法手册

目前支持的关键元素和标题词。

/// This text appears in the top **Summary** section.
/// These top lines appears before the **Declaration** heading.
/// 
/// - Author: Firstname Lastname
/// - Version: 0.1
/// 
/// Leave a blank line to separate further text into paragraphs.
/// 
/// | key   | value |
/// |-------|-------|
/// | abc   | 123   |
/// 
/// Example code block:
/// 
/// ``` swift
/// // Create an integer, and do nothing with it
/// let myInt = 42
/// doNothingReally(myInt)
/// ```
/// 
/// Bulleted lists can use `-`, `+` or `*`:
/// 
/// - Text can be *emphasised*
/// - Or **strong**
/// - You can use backticks for `code(012)` 012
/// 
/// Lists can be numbered:
/// 
/// 1. The numbers you use make no difference
/// 2. The list will still be ordered
/// 3. But be sensible and just use 1, 2, 3 etc…
///
/// - See Also: [DocD Reference](https://www.swift.org/documentation/docc/)
/// - See Also: <https://www.swift.org/documentation/docc/>
///
/// - Date: 2023.05.12
/// - Copyright: @whomever
/// - Experiment: This may or may not work as expected.
/// - Invariant: `xyz` will not change during execution
/// - Attention: Look here!
/// - Note: Whether the weather be fine, or whether the weather be…
/// - Postcondition: `address` will be updated
/// - Precondition: `person` must be non-nil
/// - Remark: This is remarkable.
/// - Requires: `Contacts` framework
/// - Requires: macOS version 12 or better 
/// - Since: The Beginning Of Time
/// - Todo: Just one more task
/// - Tip: Lorem ipsum
/// - Warning: warning, warning
///
/// - Important: This needs to be read.
///
/// - Throws: nothing
/// 
/// - Parameters:
///   - int: A pointless `Int` parameter.
///   - bool: This `Bool` isn't used, but its default value is `false`  anyway…
/// 
/// - Returns: Nothing useful.
func doNothingReally(int: Int, bool: Bool = false) -> String {
    return "Totally contrived."
}

在本文撰写时,See Also:运行良好。然而,SeeAlso:目前无法工作,需要等待支持遗留- SeeAlso: callout asides#461的一般发布。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接