试试这个,信用Swift Associated Type Design Patterns
protocol ConfigureCell {
associatedtype DataType
func configure(data: DataType)
}
class AbstractCell<T: Codable>: UITableViewCell, ConfigureCell {
func configure(data: T) {
}
var delegate: AbstractCellDelegate?
}
class UserCell: AbstractCell<UserDetail> {
override func configure(data: UserDetail) {
}
}
protocol AbstractCellDelegate {
func cellBtnClicked(model: Codable, index: Int, cell: Any)
func cellBtnClicked(model: Codable, index: Int, cell: Any, action: String)
func cellBtnClicked(model: Codable?, index: Int, cell: Any, action: String)
}
extension AbstractCellDelegate {
// dont need them
func cellBtnClicked(model: Codable, index: Int, cell: Any) {}
func cellBtnClicked(model: Codable, index: Int, cell: Any, action: String) {}
func cellBtnClicked(model: Codable?, index: Int, cell: Any, action: String) {}
}
protocol CellDelegate: AbstractCellDelegate {
associatedtype DataType: Codable
func cellBtnClicked(model: DataType, index: Int, cell: AbstractCell<DataType>)
func cellBtnClicked(model: DataType, index: Int, cell: AbstractCell<DataType>, action: String)
func cellBtnClicked(model: DataType?, index: Int, cell: AbstractCell<DataType>, action: String)
}
struct UserDetail: Codable {
}
struct MyDataType: Codable {
}
class MyViewController: CellDelegate {
func cellBtnClicked(model: MyDataType, index: Int, cell: AbstractCell<MyDataType>) {
}
func cellBtnClicked(model: MyDataType, index: Int, cell: AbstractCell<MyDataType>, action: String) {
}
func cellBtnClicked(model: MyDataType?, index: Int, cell: AbstractCell<MyDataType>, action: String) {
}
typealias DataType = MyDataType
}
编辑
你可以试试这个
protocol ConfigureCell {
associatedtype DataType
func configure(model: DataType)
}
protocol DelegateCell {
associatedtype DataType
func btnTap(model: DataType)
}
class UserCell: ConfigureCell, DelegateCell {
typealias DataType = UserDetail
var btnTapHandler: ((DataType) -> Void)?
func btnTap(model: DataType) {
btnTapHandler?(model)
}
var model: DataType?
func configure(model: DataType) {
self.model = model
}
@IBAction func tap() {
if let model = model {
btnTap(model: model)
}
}
}
struct UserDetail {
var name = "Manas"
}
class TableViewController {
var items = [UserDetail]()
func cellForIndexPath(row: Int) {
let cell = UserCell()
cell.configure(model: items[row])
cell.btnTapHandler = { data in
print(data.name)
}
}
}