Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift函数参数:名称和对象类型_Swift_Parameters_Named Parameters - Fatal编程技术网

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

Swift函数参数:名称和对象类型,swift,parameters,named-parameters,Swift,Parameters,Named Parameters,我有一个关于函数参数语法的问题。以这个函数为例: func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ //code goes here } 在函数定义中,每个参数都有一个变量名和一个冒号,后跟一个对象类型 问题 在上面的函数中,为什么有两个名称cellforrowatinexpath和indexPath 我应该使用i

我有一个关于函数参数语法的问题。以这个函数为例:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    //code goes here    
}
在函数定义中,每个参数都有一个变量名和一个冒号,后跟一个对象类型

问题

在上面的函数中,为什么有两个名称
cellforrowatinexpath
indexPath

我应该使用
indexPath
变量吗


这里涉及到什么概念?

cellforrowatinexpath
是实际
indepath
参数(也称为内部参数)的命名(或外部)参数。命名参数是调用函数时使用的参数。简单地说,您可以将参数命名为与实际输入变量名称不同的名称

简化示例

在下面的示例中,我创建了一个命名参数为
germanShepherd
的简单对象:

func getDog(barks: Bool, germanShepherd dog: String) {}
然后,当我调用我使用的函数时:

getDog(true, germanShepherd: myValue)
在我的简单示例中,命名参数有助于消除“dog”参数的歧义,正如
cellforrowatinexpath
有助于消除
indexPath
参数的歧义

删除命名参数

您还可以通过使用下划线代替命名参数来删除命名参数,如下所示:

func getDog(barks: Bool, _ dog: String) {}

getDog(true, "yes")
当然,这些都可能在Swift 3中发生变化


在objective-c中(这一概念也在swift中实现),有一些被称为“命名”参数的东西,可以帮助您了解您需要什么类型的信息来提供功能以完成其工作
indepath
是您将在函数中使用的实际变量,而
cellforrowatinexpath
只不过是一个命名参数,告诉您此处的内容。我希望这有帮助

@robmayoff谢谢你
cellforrowatinexpath
是外部参数名,而
indexPath
是内部参数名