Alican Yilmaz Alican Yilmaz - 1 year ago 75
Swift Question

Swift: About Protocols and Delegation pattern

i want to ask that how the protocols and delegation patterns functions in Swift.

I have an application that let me try the google ad sdk on iOS platform. But i'm missing something and confused about how the methods works.

I have some codes like these;

import UIKit
import GoogleMobileAds

class ViewController: UIViewController, GADInterstitialDelegate {

@IBOutlet weak var bannerView: GADBannerView!
let request = GADRequest()
var interstitial: GADInterstitial!

@IBOutlet weak var mylbl: UILabel!
override func viewDidLoad() {
bannerView.adUnitID = "xxx"
bannerView.rootViewController = self
interstitial = createAndLoadInterstitial()

func createAndLoadInterstitial() -> GADInterstitial {
let interstitial = GADInterstitial(adUnitID: "xxx")
interstitial.delegate = self
return interstitial

func interstitialDidDismissScreen(ad: GADInterstitial!) {
interstitial = createAndLoadInterstitial()
mylbl.text = "No ad"


func interstitialDidReceiveAd(ad: GADInterstitial!) {
mylbl.text = "received ad"

@IBAction func touched(sender: AnyObject) {

if interstitial.isReady
mylbl.text = "Not Ready!"
override func didReceiveMemoryWarning() {
// Dispose of any resources that can be recreated.


For the code above, i'm aware of that the protocols blueprints of methods and properties to adopt a class or struct or enum. The methods or properties defined in the protocol should be implemented on the class that adopted by the related delegate.

I want to ask that and cofused point: OK the method which is named "interstitialDidDismissScreen" inherited from the delegate "GADInsterstitialDelegate" but how the method handled by pressing the close button of the interstitial ad. Where the engineers of Google implemented and how they succeed this behavior. Thanks for your help.

Good hacks,

Answer Source

The wording of your question is garbled and hard to figure out.

A protocol is basically a contract. It says that objets that conform to the protocol promise to provide the properties, and respond to the methods that the protocol defines.

When you say

someObject.delegate = self

You are passing a pointer to yourself to the other object. This is like giving somebody your phone number and saying "Please run these errands for me. If you have any questions, call me at this number. Also please call me when the errands are done."

Since the other object knows that it's delegate conforms to a specific protocol, it knows what messages it can send over the phone (what messages it can send to the delegate)

I suspect the methods interstitialDidReceiveAd(ad: GADInterstitial!) and interstitialDidDismissScreen(ad: GADInterstitial!) are delegate methods.

When the interstitial object needs to send messages to it's delegate, it calls these methods.