I have a question regarding the syntax of function parameters. Take this function for example:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
//code goes here
}
In the function definition, each parameter has a variable name and a colon followed by an object type.
Question
In above function why are there two names? cellForRowAtIndexPath
and indexPath
.
Should I be using the indexPath
variable?
What concept is involved here?
In objective-c (this concept was also implemented in swift) there are these things called "named" parameters that assist you in letting you know as to what type of information you need to supply the function for it to do its job. indexPath
is the actual variable you'll use within your function, while cellForRowAtIndexPath
is nothing more than a named parameter telling you what goes here. I hope that helps!
cellForRowAtIndexPath
is a named (or external) parameter for the actual indexPath
parameter also known as the internal parameter. The named parameter is what you use when calling the function. Put simply, you have the ability to name a parameter something different than the name of your actual input variable name.
A simplified example
In the following example I've made a simple object with a named parameter of germanShepherd
:
func getDog(barks: Bool, germanShepherd dog: String) {}
Then when I call the function I use:
getDog(true, germanShepherd: myValue)
In my simple example the named parameter can help clear up the ambiguity of the "dog" parameter, just as cellForRowAtIndexPath
helps to clear up the ambiguity of the indexPath
parameter.
Removing the named parameter
You also have the option to remove the named parameter by utilizing an underscore in place of the named parameter like so:
func getDog(barks: Bool, _ dog: String) {}
getDog(true, "yes")
Of course this is all subject to change in Swift 3 !
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.