Fred Clausen Fred Clausen - 26 days ago 13
Swift Question

Swift method parameters in documentation

I sometimes see Swift methods documented as

application(_:didFinishLaunchingWithOptions:)
or
tableView(_:cellForRowAtIndexPath:)
. Where are these generalised method documentation conventions documented? For example: where can I see what the underscore means, how to interpret multiple method parameters documented in this fashion, etc.

Rob Rob
Answer

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, both 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).