swift generic and dynamic method dispatch

≡放荡痞女 提交于 2021-01-28 06:57:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!