Search code examples
swiftswift2protocolsprotocol-extension

How to set delegate in a protocol extension


I have multiple view controllers which shows same kind of cells. I want to set delegate in a protocol extension like this:

class ProductsViewController: UIViewController, ProductShowcase {
    //other properties
    @IBOutlet weak var productCollectionView: UICollectionView!
    var dataSource: DataSource!

    override func viewDidLoad() {
        super.viewDidLoad()

        setupDataSource()

        setupCollectionView()
    }

    func didSelectProduct(product: Product) {
        print(product)
    }

    //other functions
}

protocol ProductShowcase: UICollectionViewDelegate {
    var dataSource: DataSource! { get set }
    var productCollectionView: UICollectionView! { get }

    func didSelectProduct(product: Product)
}

extension ProductShowcase {
    func setupCollectionView() {
        productCollectionView.registerClass(ProductCollectionViewCell.self, forCellWithReuseIdentifier: "productCell")
        productCollectionView.dataSource = dataSource
        print(self) //prints ProductsViewController
        productCollectionView.delegate = self // 
        print(productCollectionView.delegate) //prints optional ProductsViewController
    }
}

extension ProductShowcase {
    //this delegate method is not called
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        didSelectProduct(dataSource.dataObjects[indexPath.row])
    }
}

When didSelectItemAtIndexPath is implemented in ProductsViewController it gets called. Is there something I missed or is this a wrong approach?


Solution

  • It is a Objective-C interoperability limitation. You are not allowed to implement protocols with optionals function in protocol extension like you wanted (protocols which are from Objective-C type UIKit control's delegates and datasources, etc.). You can have default implementation of only protocol that are written like:

    // No, @objc in the front of protocol. (i.e. objc-type protocol)
    protocol X {
    }