问题
I create an extension for UITableViewCell, and give the default method.
Through the set<T: UITableViewCell>
method, I want the setupData
method can dynamic dispatch by the cell type. But it always failed, and the result jump to the fatalError.
import UIKit
class cell: UITableViewCell {
func setupData<T>(_ data: T) {
print(#function)
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
set(cell.self)
}
func set<T: UITableViewCell>(_ t: T.Type) {
let cell = T()
cell.setupData(1)
}
}
protocol Action {
func setupData<T>(_ data: T)
}
extension Action {
func setupData<T>(_ data: T) {
fatalError("This method is abstract, need subclass.")
}
}
extension UITableViewCell: Action {}
回答1:
Things in an extension are always statically dispatched. In set
, cell.setupData(1)
is already bound to the implementation in the extension at compile time.
I don't see why you would need this extension anyway, you only need:
class cell: UITableViewCell, Action {
func setupData<T>(_ data: T) {
print(#function)
}
}
protocol Action {
func setupData<T>(_ data: T)
init()
}
...
func set<T: Action>(_ t: T.Type) {
let cell = T()
cell.setupData(1)
}
来源:https://stackoverflow.com/questions/56413484/swift-generic-and-dynamic-method-dispatch