Here's an example of what I'm talking about: https://developer.apple.com/documentation/foundation/nsmutableorderedset/1410287-insert
The insert function is shown as insert(_:at:)
When it's actually used, the insert function looks more like:
namesArray.insert("John", at: 3)
There's no :
after "John"
(though I suppose it could be "John":String
-- is that what it's there for?), and the ,
that actually needs to go there is not mentioned in the function signature in the documentation. Am I just supposed to know/assume that the comma goes there when I actually use it? Is this the case for all Swift functions?
Please note that this is not a question about the underscore, _
-- I understand why it's there and what it's for. I'm specifically asking about the reasons for including :
and not including ,
in the function signature.
The convention, frequently seen in documentation, is a concise way of referring to a function, using only the function name and argument labels.
So consider this function declaration:
func insert(_ objects: [Any], at indexes: IndexSet)
This is
insert
;objects
, this parameter has no argument label (designated with the _
) and has a type of [Any]
; andindexes
, its argument label is at
and has a type of IndexSet
.So you call it like so:
insert(someObjects, at: someIndex)
When you call it, you don’t care what the parameter names that are used inside that function, but rather just what the argument labels are. So, the convention when referring to that method in documentation is to omit the parameter names and types and just use the function name and the argument labels, but no comma:
insert(_:at:)
Note, you’d never actually use this syntax in your code. This is just a documentation convention employed to distill long function declarations down to something more manageable and concise:
For more information about argument labels and parameter names, see Function Argument Labels and Parameter Names
A :
in the function signature always means an input argument to the function. The function signature contains the argument label followed by a :
. The _
means there's no argument label, in which case you can omit the :
as well when supplying that specific input argument to the function call.
This is exactly what you see with the insert(_:at:)
function. You supply two input arguments to it, "John"
and 3
, but it only needs an argument label for the second input argument, hence you only need one :
. It's also important to note that at call time, you separate the input arguments using ,
, not :
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With