Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 generics: issue with setting UICollectionViewDatasource & Delegate for a UICollectionView inside UITableViewCell

I'm in the process of translating my app to Swift 3. I stumbled upon an issue with using a clean way of setting datasource and delegate for a UICollectionView inside a UITableViewCell, described here.

The code is as follows:

func setCollectionViewDataSourceDelegate<D: protocol<UICollectionViewDataSource, UICollectionViewDelegate>>
(_ dataSourceDelegate: D, forRow row: Int) {

collectionView.delegate = dataSourceDelegate
collectionView.dataSource = dataSourceDelegate
collectionView.tag = row
collectionView.reloadData()}

And it throws a warning, stating:

'protocol<...>' composition syntax is deprecated; join the protocols using '&'

When I accept the suggested solution, it changes the D: protocol<UICollectionViewDataSource, UICollectionViewDelegate> into a D: (UICollectionViewDatasource & UICollectionViewDelegate) call, and instead throws an error:

Expected a type name or protocol composition restricting 'D'

I'd be much obliged if someone with a better understanding of Swift 3 generics than myself could suggest a solution.

like image 807
michalronin Avatar asked Apr 28 '26 07:04

michalronin


2 Answers

No need to use protocol<> because the compiler already knows that. Just join the protocols like this: D: UITableViewDelegate & UITableViewDataSource

like image 75
kientux Avatar answered Apr 30 '26 21:04

kientux


setCollectionViewDataSourceDelegate for swift3

extension PollTableViewCell {

      func setCollectionViewDataSourceDelegate<D: UICollectionViewDataSource & UICollectionViewDelegate>(_ dataSourceDelegate: D, forRow row: Int) {

        theCollectionView.delegate = dataSourceDelegate
        theCollectionView.dataSource = dataSourceDelegate
        theCollectionView.tag = row
        theCollectionView.setContentOffset(theCollectionView.contentOffset, animated:false) // Stops collection view if it was scrolling.
        theCollectionView.reloadData()
    }

    var collectionViewOffset: CGFloat {
        set {
            theCollectionView.contentOffset.x = newValue
        }

        get {
            return theCollectionView.contentOffset.x
        }
    }
}
like image 40
Ganesh Manickam Avatar answered Apr 30 '26 21:04

Ganesh Manickam