快速的通用和动态方法分派 [英] swift generic and dynamic method dispatch

查看:31
本文介绍了快速的通用和动态方法分派的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为UITableViewCell创建一个扩展,并提供默认方法.通过 set< T:UITableViewCell> 方法,我希望 setupData 方法可以按单元格类型动态分配.但是它总是失败,结果跳到fatalError.

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 {}


推荐答案

扩展中的内容始终静态分配.在 set 中, cell.setupData(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)
}

这篇关于快速的通用和动态方法分派的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆