Reputation: 2633
I'm learning Swift (following Apple's tutorials) and I've come across this notation:
optional func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : AnyObject])
In this context what does the _
mean? And what is the relation between didFinishPickingMediaWithInfo
and the info dictionary (obviously it is not the type since that is provided after the colon)?
Upvotes: 0
Views: 353
Reputation: 7198
Check this article http://natashatherobot.com/swift-parameter-names-in-functions/
It explains the meaning of the use of the "_" in a function/method signature.
Upvotes: 0
Reputation: 72750
When defining parameters for a function or method, besides the type, each parameter must have a local name, which identifies the name of the variable accessible from the body of the function, but it can also have an external name, which is used when invoking the function.
func doSomething(externalName internalName: Int) {
print(internalName)
}
doSomething(externalName: 4)
The underscore in place of the external name means that no external name is defined for that parameter. In the above example":
func doSomething(_ internalName: Int) {
print(internalName)
}
it means the function is invoked by passing the parameter without being prefixed by the external name:
doSomething(5)
External names are useful to identify what each parameter is for, making code easier to read. For instance, compare this:
update(33, 1, data)
with this:
update(invoiceId: 33, itemId: 1, invoiceDetails: data)
Because of its usefulness, Swift automatically "promotes" local names to external names when not explicitly specified. In Swift 1.x:
In Swift 2.0 global functions follow the same rule as methods.
Auto generating external names means for example that a function like this:
func updateInvoice(invoiceId: Int, invoiceDetailId: Int, invoiceDetail: data)
will have its signature automatically updated to:
func updateInvoice(invoiceId: Int, invoiceDetailId invoiceDetailId: Int, invoiceDetail invoiceDetail: data)
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^
with the automatic addition of an external name to both the 2nd and the 3rd (i.e. all parameters after the 1st).
In your case:
optional func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
the first underscore means: do not use nor generate an external name for this parameter. As for the 2nd parameter, it is referenced as didFinishPickingMediaWithInfo
when invoking the function, but it will be available to the imagePickerController
methood as a variable named info
.
Recommended reading: Function Parameter Names
Upvotes: 3