为什么 Xcode 自动修复创建两个具有相同名称`func tableView` 的方法?

Lag*_*hen 0 uitableview ios swift

我是 swift 编程语言的新手。我已经看到在 Swift 中创建表时,您必须在 ViewController 类中实现两个扩展UITableViewDelegate, 的方法UITableViewDataSource。我不明白的是,为什么 Xcode 的自动修复会func tableView在这个类中创建两个同名的方法?

这不会造成方法重载或导致错误吗?

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var tableView: UITableView!
    let dataArray = ["firt", "second", "third", "four", "five", "six"]

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let videoCell = tableView.dequeueReusableCell(withIdentifier: "video title", for: indexPath)

        return videoCell
    }


    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        tableView.dataSource = self
        tableView.dataSource = self
    }

}
Run Code Online (Sandbox Code Playgroud)

Jul*_*tri 5

即使它们具有相同的函数名称 tableView

它们是非常不同的功能。它们都符合 UITableView 委托,并且基于其协议方法会影响 tableView 的不同功能。

didSelectRowAt
Run Code Online (Sandbox Code Playgroud)

不一样

cellForRowAt
Run Code Online (Sandbox Code Playgroud)
  • Did Select row at 仅在您明显选择单元格时触发

  • 行单元格被视为“主要”tableView 函数,因为此函数填充您的 tableView 数据单元格。

--EDIT 基于下面的 Duncan C 评论。

“您的示例函数的名称不是 tableView,函数的名称是 tableView(_:cellForRowAt:)(参数实际上是函数名称的一部分,或者更确切地说是函数“签名”。)“

这是描述答案的绝佳方式。

编辑2----

此外,这在 swift 编程中很常见。最直接的例子是collectionView。它使用几乎相同的命名约定。

cellForRowAt
Run Code Online (Sandbox Code Playgroud)

didSelectRowAt
Run Code Online (Sandbox Code Playgroud)

还有许多其他委托方法,您会遇到与您在问题中描述的情况相同的情况。

  • 添加 Julian 和 xTwistedDx,示例函数的名称不是 `tableView`,函数的名称是 `tableView(_:cellForRowAt:)` (参数实际上是函数名称的一部分,或者更确切地说,它是函数“签名。”) (3认同)