Abstract class in Swift

2019-06-08 00:47发布

问题:

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