简体   繁体   English

Swift函数参数:名称和对象类型

[英]Swift function Parameter: Name and Object type

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 . cellForRowAtIndexPathindexPath

Should I be using the indexPath variable? 我应该使用indexPath变量吗?

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. 在objective-c(这个概念也在swift中实现)中,有一些称为“命名”参数的东西可以帮助您了解为其提供功能所需的信息类型。 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. indexPath是你在函数中使用的实际变量,而cellForRowAtIndexPath只不过是一个命名参数,告诉你这里有什么。 I hope that helps! 我希望有所帮助!

cellForRowAtIndexPath is a named (or external) parameter for the actual indexPath parameter also known as the internal parameter. cellForRowAtIndexPath是实际indexPath参数的命名 (或外部)参数,也称为内部参数。 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 : 在下面的例子中,我创建了一个带有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. 在我的简单示例中, 命名参数可以帮助消除“dog”参数的歧义,就像cellForRowAtIndexPath有助于消除indexPath参数的歧义indexPath

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 3中都有变化!

swift evolution 快速进化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM