Swift Documentation Comments

2019-03-09 11:03发布

问题:

I have a few questions about Swift documentation comments.

  1. Is there anyway 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 3 other related methods within the generated documentation.

  2. Is there any warning tag in swift? I know in objective-c it allowed you to do @warning and get a bolded warning in the documentation that is generated. However, :warning: does nothing in swift documentation comments, so I was curious if there was another way.

  3. Is there any way to make your documentation into an HTML file that is a similar format as the Apple Documentation. I know in other IDEs for other languages, such as Eclipse, you can just generate html documentation for your code. Does XCode have this?

回答1:

You can use markup to write both playground and code documentation comments.

  • For rich playground documentation use //: or /*: */
  • For code documentation use /// or /** */

Example

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

Answers to your questions

Ad. 1. No. While there is a SeeAlso markup tag, it's not yet clever enough to link to related symbols inside your or third-party library.

Ad. 2. Yes, there is a Warning markup tag. See my above example.

Ad. 3. Altough Xcode can generate XML representation of the documentation comments, it cannot produce a HTML file. I recommend using jazzy for that.



回答2:

Xcode 7.0 beta 4

The notation has been changed (:param: does not work anymore ...)

/// Creates the string representation of the poo with requested size.
///
/// - warning: Be carefull! Poos can hurt.
/// - parameter size: requested size of the poo
/// - returns: string representation of the poo
func makePoo(size: String) -> String
{
    return "Ouch. This is \(size) poo!"
}

And it looks like this:

You can use either /// or /** */



回答3:

(3) To generate your documentation in HTML (or even generate docsets), I strongly recommend jazzy which was built for that purpose.

Even if it's still WIP, it works really well and generate documentation with similar presentation to the Apple documentation