iOS Interview: Delegation Pattern in Swift

in #ios6 years ago (edited)

It's a continuation of my previous post about implementing delegate pattern in iOS. This time it is written in Swift.

App Delegate

import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, TapProtocol{
    func buttonTapped() {
        print("Button Tapped")
    }
    
    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        if let w =  self.window,let vc = w.rootViewController as? ViewController
        {
            vc.delegate = self
        }
        return true
    }
}

View Controller

protocol TapProtocol:class {
    func buttonTapped()
}

class ViewController: UIViewController {
    weak var delegate:TapProtocol?

    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    @IBAction func buttonTapped(_ sender: Any) {
        self.delegate?.buttonTapped()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}