michalronin michalronin - 1 year ago 140
Swift Question

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

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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download