Protocol/delegates in Swift 3.0

Protocol/delegates in Swift 3.0

I declare this day a fine day having discovered non-Objective-C protocols! No more @objc protocol usage. Now it’s as simple as something like this:

protocol myDelegate {
    func report(info:String)
}

class MyClass: NSObject {
    var delegate:myDelegate?
    var serviceType = "hephaestus"

    init(withServiceType: String){
        self.serviceType = withServiceType
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            self.delegate?.report(info: UIDevice.current.name)
        }
    }

    convenience override init() {
        self.init(withServiceType: "hephaestus")
    }
}

And then in implementation

import UIKit

class ViewController: UIViewController, myDelegate {
    
    // Delegate method
    func report(info: String) {
        print("delegate: \(info)")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let mc = MyClass()
        mc.delegate = self
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

This is a really simple example, but it works and seems cleaner to me in Swift.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.