1

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?

1
  • @robmayoff thank you! cellForRowAtIndexPath is the external parameter name while indexPath is the internal parameter name Commented Feb 10, 2016 at 0:58

2 Answers 2

2

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!

Sign up to request clarification or add additional context in comments.

Comments

1

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!

swift evolution

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.