Ios – How to use Swift documentation comments

documentation-generationiosswiftxcodexcode6

I have a few questions about Swift documentation comments:

  1. 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.

  2. 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.

  3. 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?

Best Answer

This answer was last revised for Swift 5.2 and Xcode 11.4.


You can use markup to write standard code documentation (using /// or /** */) and rich playground documentation (using //: or /*: */).

/// This function returns a welcoming string for a given `subject`.
///
/// ```
/// print(hello("World")) // Hello, World!
/// ```
///
/// - Warning: The returned string is not localized.
/// - Parameter subject: The subject to be welcomed.
/// - Returns: A hello string to the `subject`.
func hello(_ subject: String) -> String {
    return "Hello, \(subject)!"
}

As for documenting related symbols, there is a SeeAlso markup tag but requires you to write an explicit URL to your related symbol's documentation page.

If you want to generate HTML documentation index for your project, I recommend checking out jazzy and swift-doc. They're both amazing open-source projects, and are even used by Apple itself.