gpt4 book ai didi

ios - 无法使用类型为 '*' 的参数列表调用 '' - Swift 泛型问题

转载 作者:行者123 更新时间:2023-11-28 10:05:08 25 4
gpt4 key购买 nike

我有一个通用方法,它接受一个 UITableviewCells 数组来注册一个 tableView。当我尝试注册时出现以下错误

无法使用“(nibs: [UITableViewCell.Type])”类型的参数列表调用“register”

我尝试注册的所有 UITableviewCell 都符合名为 ReusableCell 的协议(protocol)

协议(protocol)如下:

 protocol ReusableCell: class { static var identifier: String { get }}

extension ReusableCell where Self: UIView {
static var identifier: String {
return String(describing: self)
}
}

通用方法如下:

extension UITableView {
func register<T: UITableViewCell>(nibs: [T.Type]) where T: ReusableCell {
nibs.forEach { register($0.self, cellName: $0.identifier) }
}
}

我的实现如下:

class CellOne: UITableViewCell, ReusableCell {}

class CellTwo: UITableViewCell, ReusableCell {}

tableView.register(nibs: [CellOne.self, CellTwo.self])
  • 上面这行弹出错误“无法使用类型为‘(nibs: [UITableViewCell.Type])”的参数列表调用‘register’”

---已编辑---

但是如果两个单元格属于同一类,则相同的函数不会抛出任何错误

tableView.register(nibs: [CellOne.self, CellOne.self])

我在这里错过了什么?任何帮助将不胜感激

提前致谢。

最佳答案

为此您不需要泛型。您可以只使用 ReusableCell.Type。您也不需要 $0.self 因为 $0 已经是一个 Type

extension UITableView {
func register(nibs: [ReusableCell.Type]) {
nibs.forEach { self.register($0, forCellReuseIdentifier: $0.identifier) }
}
}

class CellOne: UITableViewCell, ReusableCell {}

class CellTwo: UITableViewCell, ReusableCell {}

let tableView = UITableView()

tableView.register(nibs: [CellOne.self, CellTwo.self])

关于ios - 无法使用类型为 '*' 的参数列表调用 '' - Swift 泛型问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54901715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com