Swift中的抽象类 [英] Abstract class in Swift

查看:403
本文介绍了Swift中的抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道协议和协议扩展是模拟抽象类的最佳方式,但我想要做的事情需要真正的抽象类。

I know about protocols and protocol extensions being the best way to emulate abstract classes, but what I want to do needs real abstract classes I think.

我想要一个 BaseCollectionViewCell BaseCollectionViewSource 一起工作。您将数组传递给 BaseCollectionViewSource 的子类,并实现一个返回重用标识符的方法。该单元格将由 BaseCollectionViewSource 实例化,并且具有一个方法 setData ,它将在具体的collectionViewCell中被覆盖。

I want a BaseCollectionViewCell and a BaseCollectionViewSource that work together. You'd pass an array to a subclass of the BaseCollectionViewSource and implement a method that returns a reuse identifier. The cell would be instantiated by the BaseCollectionViewSource and have a method setData that would be overridden in the concrete collectionViewCell.

我实际想做的是:

abstract class WRBaseCollectionViewCell: UICollectionViewCell {
    abstract func setData(_ data: AnyObject)
}

但是我不能用Swift来模仿这个(我想)。协议不能从类继承而且没有动态调度,这会导致我的想法无法覆盖所有内容。

But I can't emulate this with Swift (I think). Protocols can't inherit from classes and there is no dynamic dispatch, which kills my idea for everything to be overridable.

有没有人知道如何做到这一点?可能是工厂?我想尽可能简单地实现一个新的collectionView。

Does anyone have an idea how to do this? A factory maybe? I want to make this as easy as possible to implement a new collectionView.

推荐答案

作为参考,有一个建议添加抽象类/方法但目前有所不同。我猜他们会在接下来的一两年内重新检查它。

For reference, there is a proposal to add Abstract classes/methods but it is currently differed. I'm guessing they will re-examine it in the next year or two.

我完成这类事情的方法是使用相关类型的协议:

The way I accomplish this type of thing is by using protocols with associated types:

protocol ViewModelUpdatable {
    associatedtype ViewModelType
    func update(with viewModel: ViewModelType)
}

然后只需让你的课程遵守它,它就会强迫你添加:

Then simply make your class adhere to it, and it will force you to add:

func update(with viewModel: WhateverTypeYouWant) {
    //update your class
}

这种方法的优点是,可以以更通用的方式处理类,但保持类型安全。

The advantage of this approach, is it's possible to deal with a class in a more generic way, but keep type safety.

这篇关于Swift中的抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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