简体   繁体   中英

Can you extend a protocol that inherits from another protocol?

I want to create a protocol that inherits from UICollectionViewDataSource and use a protocol extension to provide a default implementation of the required UICollectionViewDataSource methods. However, when I try to declare a class that conforms to this protocol the compiler says Type 'MyClass' does not conform to protocol UICollectionViewDataSource' .

protocol MyDataSource : UICollectionViewDataSource {
    var values: [String] { get }
}

extension MyDataSource {
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = UICollectionViewCell() // TODO: dequeue
        // TODO: configure cell ...
        return cell
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.values.count
    }
}

class MyClass : NSObject, MyDataSource {
    var values = [String]()
}

I have also tried declaring the extension as the following, but still receive the same compiler error:

extension UICollectionViewDataSource where Self : MyDataSource

I have even tried expanding this to all UICollectionViewDataSources to see if inheritance part alone would work, but no dice—same error.

extension UICollectionViewDataSource

Unfortunately, what you're trying to do is impossible. The problem is that this is an Objective-C protocol. Objective-C has never heard of a protocol extension. Therefore it has no knowledge that this protocol extension is injecting two functions into MyClass. It can't see them, and so as far as it is concerned, the protocol requirements are not satisfied.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM