Swift 从单元格委托中删除重复代码

Swift 从单元格委托中删除重复代码,swift,generics,delegates,delegation,redundancy,Swift,Generics,Delegates,Delegation,Redundancy,我有一个tableview,用于配置单元格(从VC) 在cell.model的didSet中,我正在初始化单元格内容。 Cell有3个按钮,点击按钮,我通过CellDelegate通知VC protocol CellDelegate { func didTapButton1(model: Model) func didTapButton2(model: Model) func didTapButton3(model: Model) } 我的担忧:- 我不想在这里传递模型

我有一个tableview,用于配置单元格(从VC)

在cell.model的didSet中,我正在初始化单元格内容。 Cell有3个按钮,点击按钮,我通过CellDelegate通知VC

protocol CellDelegate {
    func didTapButton1(model: Model)
    func didTapButton2(model: Model)
    func didTapButton3(model: Model)
}
我的担忧:- 我不想在这里传递模型(因为它已经与单元格关联了-需要从单元格中获取模型) 我想调用没有参数的didTapButton()。然后在风投,

extension VC: CellDelegate {
//I need to fetch the model associated with the cell.
    func didTapButton1() { }
    func didTapButton2() { }
    func didTapButton3() { }
}
我可以使用闭包来实现这一点,但这里不推荐使用闭包。
任何帮助都将不胜感激。*

我猜您不想通过模型的原因是因为在所有三种方法中都有一个
模型看起来像是代码重复。好的,如果您查看了框架中的委托,例如
UITableViewDelegate
UITextFieldDelegate
,大多数(如果不是全部的话)都接受作为委托的东西作为第一个参数。
UITableViewDelegate
中的所有方法都有一个
tableView
参数。因此,您也可以遵循以下模式:

protocol CellDelegate {
    func didTapButton1(_ cell: Cell)
    func didTapButton2(_ cell: Cell)
    func didTapButton3(_ cell: Cell)
}
就我个人而言,我会在这个委托中只写一个方法:

protocol CellDelegate {
    func didTapButton(_ cell: Cell, buttonNumber: Int)
}
在VC扩展中,只需检查按钮编号,查看按下了哪个按钮:

switch buttonNumber {
    case 1: button1Tapped()
    case 2: button2Tapped()
    case 3: button3Tapped()
    default: fatalError()
}

// ...

func button1Tapped() { ... }
func button2Tapped() { ... }
func button3Tapped() { ... }

我猜你不想通过模型的原因是因为在所有三种方法中都有一个
模型
,看起来像是代码重复。好的,如果您查看了框架中的委托,例如
UITableViewDelegate
UITextFieldDelegate
,大多数(如果不是全部的话)都接受作为委托的东西作为第一个参数。
UITableViewDelegate
中的所有方法都有一个
tableView
参数。因此,您也可以遵循以下模式:

protocol CellDelegate {
    func didTapButton1(_ cell: Cell)
    func didTapButton2(_ cell: Cell)
    func didTapButton3(_ cell: Cell)
}
就我个人而言,我会在这个委托中只写一个方法:

protocol CellDelegate {
    func didTapButton(_ cell: Cell, buttonNumber: Int)
}
在VC扩展中,只需检查按钮编号,查看按下了哪个按钮:

switch buttonNumber {
    case 1: button1Tapped()
    case 2: button2Tapped()
    case 3: button3Tapped()
    default: fatalError()
}

// ...

func button1Tapped() { ... }
func button2Tapped() { ... }
func button3Tapped() { ... }

为什么不想传递模型参数?委托中只有一个函数-
didTapButton(model:buttonNumber:)
怎么样?为什么不传递model参数?如果委托中只有一个函数-
didTapButton(model:buttonNumber:)
?如果只有一个方法,我可以使用闭包回调来简化吗?VC可能有两个表视图,为了区分委托人是否在委托人中具有tableview参数,我仍然没有得到为什么必须发送该参数的支持点?-苹果的框架是有原因的,但我们为什么要这样做呢?@Nagaraj你想要的模型是正确的吗?有一个单元格参数可以获取模型。如果只有一个方法,我可以使用闭包回调更简单吗?一个VC可能有两个tableview,为了区分代理,在被代理中有tableview参数我仍然没有得到为什么我们必须发送参数的支持点?-苹果的框架是有原因的,但我们为什么要这样做呢?@Nagaraj你想要的模型是正确的吗?使用单元参数可以获取模型。