Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multiple protocols in Swift with same protocol variables?

In swift I'm implementing two protocols, GADCustomEventInterstitial and GADCustomEventBanner.

Both of these protocols require a property called delegate. delegate is a different type in each protocol, and thus a conflict arises.

 class ChartBoostAdapter : NSObject, GADCustomEventInterstitial, GADCustomEventBanner, ChartboostDelegate{
        var delegate:GADCustomEventInterstitialDelegate?; // Name conflict
        var delegate:GADCustomEventBannerDelegate?; // Name conflict
         override init(){

        }
    ...

    }
like image 685
NJGUY Avatar asked Apr 12 '15 03:04

NJGUY


3 Answers

They are libraries/frameworks it's not my definition

Then obviously you cannot make the same class adopt both protocols. But you don't really need to. Just separate this functionality into two different classes, as is evidently intended by the designer of these protocols. You are supposed to have one class that adopts GADCustomEventInterstitial and has its delegate, and another class that adopts GADCustomEventBanner and has its delegate. What reason do you have for trying to force these to be one and the same class? As in all things where you are using a framework, don't fight the framework, obey it.

like image 71
matt Avatar answered Sep 23 '22 20:09

matt


It is actually possible, I just encountered same situation. I had two different but kind of related protocols. In some cases I needed both to be implemented by delegate and in other cases only one and I didn't want to have two properties eg... delegate1, delegate2.

What you need to do is create another combined protocol that inherits from both protocols:

protocol ChartBoostAdapterDelegate: GADCustomEventInterstitialDelegate, GADCustomEventBannerDelegate { }


class ChartBoostAdapter : NSObject, GADCustomEventInterstitial, GADCustomEventBanner, ChartboostDelegate {

    weak var delegate: ChartBoostAdapterDelegate?

    override init(){

    }
    ...

}
like image 43
Matej Ukmar Avatar answered Sep 25 '22 20:09

Matej Ukmar


The simple answer is that you can't.

Maybe one protocol depends on another, in which case you would use the dependent protocol for the type of your delegate.

like image 40
Vatsal Manot Avatar answered Sep 23 '22 20:09

Vatsal Manot