I have a few questions about Swift documentation comments:
Is there a way to make a Related declarations section like some of the Apple documentation has? For example, when I Option+Click the tablewView(_:heightForRowAtIndexPath:)
method, it links me to three other related methods within the generated documentation.
Is there any warning tag in Swift? I know Objective-C allowed me to do @warning
and get a bolded warning in the generated documentation. However, :warning:
does nothing in Swift's documentation comments, so I was curious if there was another way.
Is there a way to make my documentation into an HTML file that is a similar format as the Apple Documentation? I know in other IDEs, such as Eclipse, I can generate HTML documentation for my code. Does XCode have this?
This answer was last revised for Swift 5.7 and Xcode 14.x.
DocC is Apple's documentation compiler that takes comments (plus additional resources) and produces rich documentation that can be viewed in Xcode or hosted on web.
Type ///
or /** */
to begin a documentation comment and then use DocC's special dialect of Markdown to write the content. This dialect supports many keywords like - Parameters:
for describing function arguments or - Returns:
for describing return values.
Note how the > Warning:
keyword was recognized as an aside and automatically emphasized. DocC supports multiple other aside types like Note
, Tip
and Important
.
/// Produce a greeting string for the given `subject`.
///
/// ```
/// print(hello("world")) // "Hello, world!"
/// ```
///
/// > Warning: The returned greeting is not localized. To
/// > produce a localized string, use ``localizedHello(_:)``
/// > instead.
///
/// - Parameters:
/// - subject: The subject to be welcomed.
///
/// - Returns: A greeting for the given `subject`.
func hello(_ subject: String) -> String {
return "Hello, \(subject)!"
}
DocC will automatically link (and auto-complete!) symbols wrapped in double backticks ``
. You can link to related symbols in the same type or other types in the same module.
Note that linking is limited only to public symbols and only to one module. As of today, there's no way to type e.g. ``UIView``
and have DocC automatically link it to UIKit's documentation.
DocC supports exporting your documentation into webpages. First, you need to compile your documentation by choosing Product → Build Documentation. Once the documentation is built, export its archive by clicking the More button. The archive will contain the entire documentation webpage that you can then host on your server.
The above process is a bit complicated, so there are many tools that can help you automate it. Apple offers swift-docc-plugin that you can add to your Swift package or Xcode project and configure it to run on every build. You can automate this process on CI as well.
I recommend reading the following guides to learn more about DocC: