Abstract class in Swift

I know that protocols and protocol extensions are the best way to emulate abstract classes, but what I want to do is really need real abstract classes.

I want to BaseCollectionViewCell

, and BaseCollectionViewSource

work together. You pass the array to the subclass BaseCollectionViewSource

and implement a method that returns the reuse identifier. The cell will be instantiated BaseCollectionViewSource

and will have a method setData

that will be overridden in the specific collectionViewCell.

What I really want to do is:

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

      

But I cannot imitate this with Swift (I think). Protocols cannot inherit from classes, and there is no dynamic dispatch that kills my idea of โ€‹โ€‹anything that can be overstated.

Does anyone have any idea how to do this? A factory maybe? I want to keep it as simple as possible in order to implement a new CollectionView.

+1


source to share


2 answers


There is a suggestion to add abstract classes / methods for reference , but it is different at the moment. I guess they will revise it in the next year or two.

The way I do it is using protocols with associated types:

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

      

Then just force your class to stick with it and it will force you to add:



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

      

The advantage of this approach is perhaps to deal with the class in a more general way, but still maintain type safety.

The way I'm going to sort this out is generics, but InterfaceBuilder still breaks with generics ๐Ÿ˜ญ.

+4


source


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



protocol SetDataViewCell {}

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

      

+1


source







All Articles