I have a tableView
with cells that use inheritance. There is one common ancestor, and then there are several specific implementations. The common class does not override init(style:reuseIdentifier:)
and it rather defines its own custom initializer. All the subclasses however do define this initializer, in which they call the custom one from the super class. Now in the tableView
I register the subclasses for the reuse, and I am dequeuing subclasses for reuse. Yet I get following error when I try to dequeue any of the subclasses:
fatal error: use of unimplemented initializer 'init(style:reuseIdentifier:)' for class 'milan.BotChatBaseCell'
where milan.BotChatBaseCell
is the superclass. Now milan.BotChatBaseCell
is never registered to the tableView. Any idea why is this happening?
Code:
import UIKit
class ViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(ExampleBotChatCell.self, forCellReuseIdentifier: "ExampleBotChatCell")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ExampleBotChatCell", for: indexPath) as! ExampleBotChatCell
return cell
}
}
class BotChatBaseCell: UITableViewCell {
init(style: UITableViewCellStyle, reuseIdentifier: String?, customString: String) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
print(">>>> nice \(customString)")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ExampleBotChatCell: BotChatBaseCell {
init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier, customString: "Example")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
I have just tested it, it works on Swift 3.2, but not on Swift 4.