我是Swift的新手,我已经遍历了一些教程,其中许多教程使用同一个名称多次定义了一个函数。
我习惯于其他编程语言,否则将无法执行此操作,否则将引发错误。
因此,我检查了官方的Swift手册,还检查了override关键字,以了解可以得到的结果,但是仍然无法理解以下代码:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell")
cell.textLabel?.text = "Row #\(indexPath.row)"
cell.detailTextLabel?.text = "Subtitle #\(indexPath.row)"
return cell
}
从我可以看到的函数tableView在行1和行5中进行设置,我注意到的唯一区别是第一个tableView函数返回,Int
而第二个函数返回Object
(UITableViewCell)。
在这种情况下,我从结果中看到第二个函数没有覆盖第一个函数。
这是什么意思,为什么可以用相同的名称多次定义一个函数而不覆盖它?
如果两个函数的类型不同,或者可以通过其外部参数参数标签加以区分,则可以使用两个相同的名称定义函数。函数的类型由括号中的参数Types组成,其后是->
,然后是返回Type。请注意,参数标签不是函数的类型的一部分。(但请参见下面的更新。)
例如,以下函数都具有相同的名称并且属于Type (Int, Int) -> Int
:
// This:
func add(a: Int, b: Int) -> Int {
return a + b
}
// Is the same Type as this:
func add(x: Int, y: Int) -> Int {
return x + y
}
这将产生一个编译时错误-更改标签a:b:
,以x:y:
不区分这两种功能。(但请参见下面的更新。)
以Web先生的功能为例:
// Function A: This function has the Type (UITableView, Int) -> Int
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { ... }
// Function B: This function has the Type (UITableView, NSIndexPath) -> UITableViewCell
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { ... }
// Function C: This made up function will produce a compile-time error because
// it has the same name and Type as Function A, (UITableView, Int) -> Int:
func tableView(arg1: UITableView, arg2: Int) -> Int { ... }
上面的功能A和功能B不冲突,因为它们是不同的类型。 上面的函数A和函数C确实冲突,因为它们具有相同的类型。如果类型保持不变,则更改参数标签不能解决冲突。 (请参见下面的更新。)
override
完全是一个不同的概念,我认为还有其他一些答案可以解决这个问题,因此我将跳过它。
更新:我上面写的一些不正确。的确,函数的参数标签不是其Type定义的一部分,但是它们可以用于区分具有相同Type的两个函数,只要该函数具有不同的外部标签,以便编译器可以分辨出哪个您尝试在调用它时调用的函数。例:
func add(a: Int, to b: Int) -> Int { // called with add(1, to: 3)
println("This is in the first function defintion.")
return a + b
}
func add(a: Int, and b: Int) -> Int { // called with add(1, and: 3)
println("This is in the second function definition")
return a + b
}
let answer1 = add(1, to: 3) // prints "This is in the first function definition"
let answer2 = add(1, and: 3) // prints "This is in the second function definition"
因此,在函数定义中使用外部标签将允许编译具有相同名称和相同类型的函数。因此,看起来您可以用相同的名称编写多个函数,只要编译器可以通过它们的类型或它们的外部签名标签来区分它们即可。我认为内部标签并不重要。(但是我希望如果我错了,有人会纠正我。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句