Abstract class in Swift

爷,独闯天下 提交于 2020-01-02 22:33:08

问题


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.

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.

What I practically want to do is this:

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

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.

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.


回答1:


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.

The way I'm hoping to deal with this some day is generics, but InterfaceBuilder still breaks with generics 😭.




回答2:


Hmm, not quite sure what you want. Take a look at the following protocol.

protocol SetDataViewCell {}

extension SetDataViewCell where Self: UICollectionViewCell {
    func setData(_ data: AnyObject) {}
}


来源:https://stackoverflow.com/questions/41991643/abstract-class-in-swift

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