【问题标题】:Cannot invoke '*' with an argument list of type '' - Issue with Swift Generics无法使用“”类型的参数列表调用“*” - Swift 泛型问题
【发布时间】:2019-07-20 22:52:34
【问题描述】:

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

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

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

协议如下:

 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])”的参数列表调用“注册”

---已编辑---

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

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

我在这里缺少什么?任何帮助将不胜感激

提前致谢。

【问题讨论】:

  • 通用注册函数是UITableView的扩展吗?
  • 是的,它在 UITableview 扩展中

标签: ios swift generics protocols


【解决方案1】:

您不需要泛型。你可以使用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])

【讨论】:

    猜你喜欢
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多