David Seek David Seek - 4 years ago 173
iOS Question

Swift 3 / How to reuse extensions

I'm trying to save code and refactor.

In my project I'm using the following

extension in several

The whole extension is reusable, I just need to change the name of the ViewController:

extension MyVC: GADInterstitialDelegate {

But since I'm using it in several classes, the length of those classes exceeds unnecessarily.

Is there some kind of way to reuse the extension? Something like:

func myExtension(vc: UIViewController) {
extension vc: GADInterstitialDelegate {

Called by

I know that this code is nonsense, but it provides the idea I would like to transpose. Is there anything like that? Or what would be another option to save lines of codes for extensions with repeated code? Help is very appreciated.

My Extension:

extension MyViewController: GADInterstitialDelegate {

// MARK: - Setup Ads
func setupAds() {
// Setup our interstitial ad initially
interstitial.delegate = self


// MARK: - Load Interstitial Ad
func loadFullScreenAd() {
// GADInterstitial's are single use. You have to create a new GADInterstitial for each presentation
// So, if you'd like to show more than one GADInterstitial in your apps session we need this
// This func will be used to create a new GADInterstitial after one has been displayed and dismissed
interstitial = GADInterstitial(adUnitID: getAdmobInterstitial())

interstitial.delegate = self


// MARK: - Show Interstitial Ad
func showFullScreenAd() {
// Call this function when you want to present the interstitial ad
// ie. game over, transition to another vc, etc...
// Make sure you give atleast a few seconds for this ad to load before atempting to present it
// For example, don't try to present this ad in viewDidAppear

// Check if the interstitial ad is loaded before trying to present it

if self.interstitial.isReady {

self.interstitial.present(fromRootViewController: self)

// MARK: - GADInterstitial Delegate Methods
func interstitialDidReceiveAd(_ ad: GADInterstitial!) {

func interstitialWillPresentScreen(_ ad: GADInterstitial!) {
// If you needed to pause anything in your app this would be the place to do it
// ie. sounds, game state, etc...

func interstitialDidDismissScreen(_ ad: GADInterstitial!) {
// The GADInterstitial has been shown and dismissed by the user
// Lets load another one for the next time we want to show a GADInterstitial


// If you paused anything in the interstitialWillPresentScreen delegate method this is where you would resume it

func interstitial(_ ad: GADInterstitial!, didFailToReceiveAdWithError error: GADRequestError!) {
print("interstitial didFailToReceiveAdWithError: \(error)")

Answer Source

Extend the common superclass of all affected view controllers (probably UIViewController itself), then you can use the code in all subclasses.

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