Swift Method Parameters in Documentation

How do you document the parameters of a function's closure parameter in Swift 3?

As far as I know, you can only document the closure parameters if you label them:

/// Calls bar with "Hello, world"
/// - parameter bar: A closure to call
/// - parameter theString: A string to use
func foo(bar: (theString: String) -> Void) {
bar(theString: "Hello, world")
}

This is less than ideal: it forces you to use an argument label when you call the closure, and if there are naming conflicts, there seems no way to distinguish between the two.

Edit: As @Arnaud pointed out, you can use _ to prevent having to use the parameter label when calling the closure:

/// Calls bar with "Hello, world"
/// - parameter bar: A closure to call
/// - parameter theString: A string to use
func foo(bar: (_ theString: String) -> Void) {
bar("Hello, world")
}

In fact, this is the only valid approach in Swift 3 because parameter labels are no longer part of the type system (see SE-0111).

How to use Swift documentation comments

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.

Writing Documentation

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)!"
}

Sample Image

Linking to Symbols

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.

Generating Webpages

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.

Further Reading

I recommend reading the following guides to learn more about DocC:

  • Writing Symbol Documentation in Your Source Files
  • Formatting Your Documentation Content
  • Adding Structure to Your Documentation Pages
  • Distributing Documentation to External Developers

How to document argument label and not parameter name of Swift function in XCode?

You cannot directly refer to the argument label in the documentation of a function.

As a workaround, you can mention the label in the description of the parameter, like this:

/**
- parameters:
- param: (argument label: `label`) the parameter
*/
func myFunc(label param: Int) {...}

With the usage of back-ticks, it blends in nicely with the parameter itself:

example function documentation

Swift method parameters in documentation

The convention is illustrated in The Swift Programming Language: Functions. This is the external signature of the function, i.e. what you need to know in order to call it. It consists of the function name, plus all of the argument labels for all of the parameters of that function.

Consider

func greet(person: String) -> String {
...
}

This is the greet(person:) function.

But consider the following, slightly more complicated, Swift 3 UITableViewDataSource method:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
}

Here, each of these two parameters has both an argument label (what is used when the function is called) followed by a parameter name (what is used to refer to that parameter inside the function itself). In this case, the first parameter has no argument label (designated by _), but the name is tableView. The second parameter's argument label is cellForRowAt, and the name is indexPath.

In this case, you'll see the above UITableViewDataSource method referenced as tableView(_:cellForRowAt:): The function name is tableView, the first parameter has no argument label (designated by _), and the second parameter has an argument label of cellForRowAt.


As an aside, in Swift version 2, the first parameter's argument label would default to _ (i.e. no label) unless explicitly specified otherwise. Effective Swift 3, the first parameter works the same all of the other parameters, defaulting to whatever the parameter name was (which is why you'll see _ explicitly referenced in this case, to explicitly specify that this Swift 3 function's first parameter doesn't have a label).

How to document optional closure function parameters?

I cannot tell if that is intentional or a bug, but a workaround is
to declare the parameter type using Optional instead of ?:

/// An example function.
/// Documentation goes here.
///
/// - Parameters:
/// - optionalClosure: An optional closure.
/// - aClosureParameter: This **will** be displayed.
func exampleMethod(optionalClosure: Optional<(_ aClosureParameter: Bool) -> Void>) {
// Do something
}

Sample Image

How can I properly document a method with a completion handler in iOS swift

/**
Sends an API request to 4sq for venues around a given location with an optional text search

:param: location A CLLocation for the user's current location
:param: query An optional search query
:param: completion A closure which is called with venues, an array of FoursquareVenue objects

:returns: No return value
*/
func requestVenues(location: CLLocation, query: String?, completion: (venues: [FoursquareVenue]?) -> Void) { … }

taken from https://thatthinginswift.com/documentation-and-quick-help/

Swift documentation: instance/type property/method notation

Unfortunately Swift does not have an official or widely-accepted notation to distinguish type properties/methods and instance properties/methods with type name prefixed form.

(So, usual Swift programmers (even expert) cannot understand what you are asking.)

Type name prefixed form is actually used in the Swift book, but not so often.

As far as I checked:

  • In some parts, type property is referred to in a form like UInt32.max, but as you see this is just using actual notation valid as Swift expression.

  • In some other parts, type method is referred to as a form like LevelTracker.unlock(_:), but this also is a valid expression in Swift and I'm not sure Apple is using this as a documentation notation for type method. I cannot find an example in the Swift book with a short glance, but initializers are often referred to in a form like String.init(data:encoding:) and this is also a valid expression in Swift.

  • For other cases, instance methods or properties are referred to as instanceVar.methodName(_:) or instanceVar.propertyName, of course instanceVar appears in a nearby code snippet and is not a type name, this actually is not what you are looking for.

And as you already know, in Apple's official references, methods or properties are shown with heading Instance method, Type method , Instance Property or Type Property. Or prefixed with class/static var/let, class/static func, var/let or func.

I cannot find an example with a very short survey, but some articles (including Apple's) may be referring to an instance method also in a form TypeName.methodName(_:) (or instance property as well.) Seems Swift community thinks distinguishing type members and instance members is not important.

I could not take much time, but seems it is obvious that

Swift does not have an official or widely-accepted notation to distinguish type properties/methods and instance properties/methods with type name prefixed form.

Maybe you need to write something like instance method Array.append(_:) to represent Array#append(_:).

(To note, Array.append(_:) is also a valid expression in Swift.)



Related Topics



Leave a reply



Submit