Delegates in swift?

171,745

Solution 1

It is not that different from obj-c. First, you have to specify the protocol in your class declaration, like following:

class MyClass: NSUserNotificationCenterDelegate

The implementation will look like following:

// NSUserNotificationCenterDelegate implementation
func userNotificationCenter(center: NSUserNotificationCenter, didDeliverNotification notification: NSUserNotification) {
    //implementation
}

func userNotificationCenter(center: NSUserNotificationCenter, didActivateNotification notification: NSUserNotification) {
    //implementation
}

func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool {
    //implementation
    return true
}

Of course, you have to set the delegate. For example:

NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self;

Solution 2

Here's a little help on delegates between two view controllers:

Step 1: Make a protocol in the UIViewController that you will be removing/will be sending the data.

protocol FooTwoViewControllerDelegate:class {
    func myVCDidFinish(_ controller: FooTwoViewController, text: String)
}

Step2: Declare the delegate in the sending class (i.e. UIViewcontroller)

class FooTwoViewController: UIViewController {
    weak var delegate: FooTwoViewControllerDelegate?
    [snip...]
}

Step3: Use the delegate in a class method to send the data to the receiving method, which is any method that adopts the protocol.

@IBAction func saveColor(_ sender: UIBarButtonItem) {
        delegate?.myVCDidFinish(self, text: colorLabel.text) //assuming the delegate is assigned otherwise error
}

Step 4: Adopt the protocol in the receiving class

class ViewController: UIViewController, FooTwoViewControllerDelegate {

Step 5: Implement the delegate method

func myVCDidFinish(_ controller: FooTwoViewController, text: String) {
    colorLabel.text = "The Color is " +  text
    controller.navigationController.popViewController(animated: true)
}

Step 6: Set the delegate in the prepareForSegue:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "mySegue" {
        let vc = segue.destination as! FooTwoViewController
        vc.colorString = colorLabel.text
        vc.delegate = self
    }
}

And that should work. This is of course just code fragments, but should give you the idea. For a long explanation of this code you can go over to my blog entry here:

segues and delegates

If you are interested in what's going on under the hood with a delegate I did write on that here:

under the hood with delegates

Solution 3

Delegates always confused me until I realized that a delegate is just a class that does some work for another class. It's like having someone else there to do all the dirty work for you that you don't want to do yourself.

I wrote a little story to illustrate this. Read it in a Playground if you like.

Once upon a time...

// MARK: Background to the story

// A protocol is like a list of rules that need to be followed.
protocol OlderSiblingDelegate: class {
    // The following command (ie, method) must be obeyed by any 
    // underling (ie, delegate) of the older sibling.
    func getYourNiceOlderSiblingAGlassOfWater()
}

// MARK: Characters in the story

class BossyBigBrother {
    
    // I can make whichever little sibling is around at 
    // the time be my delegate (ie, slave)
    weak var delegate: OlderSiblingDelegate?
    
    func tellSomebodyToGetMeSomeWater() {
        // The delegate is optional because even though 
        // I'm thirsty, there might not be anyone nearby 
        // that I can boss around.
        delegate?.getYourNiceOlderSiblingAGlassOfWater()
    }
}

// Poor little sisters have to follow (or at least acknowledge) 
// their older sibling's rules (ie, protocol)
class PoorLittleSister: OlderSiblingDelegate {

    func getYourNiceOlderSiblingAGlassOfWater() {
        // Little sis follows the letter of the law (ie, protocol),
        // but no one said exactly how she had to respond.
        print("Go get it yourself!")
    }
}

// MARK: The Story

// Big bro is laying on the couch watching basketball on TV.
let bigBro = BossyBigBrother()

// He has a little sister named Sally.
let sally = PoorLittleSister()

// Sally walks into the room. How convenient! Now big bro 
// has someone there to boss around.
bigBro.delegate = sally

// So he tells her to get him some water.
bigBro.tellSomebodyToGetMeSomeWater()

// Unfortunately no one lived happily ever after...

// The end.

In review, there are three key parts to making and using the delegate pattern.

  1. the protocol that defines what the worker needs to do
  2. the boss class that has a delegate variable, which it uses to tell the worker class what to do
  3. the worker class that adopts the protocol and does what is required

Real life

In comparison to our Bossy Big Brother story above, delegates are often used for the following practical applications:

  1. Communication: one class needs to send some information to another class.
  2. Customization: one class wants to allow another class to customize it.

The great part is that these classes don't need to know anything about each other beforehand except that the delegate class conforms to the required protocol.

I highly recommend reading the following two articles. They helped me understand delegates even better than the documentation did.

One more note

Delegates that reference other classes that they do not own should use the weak keyword to avoid strong reference cycles. See this answer for more details.

Solution 4

I got few corrections to post of @MakeAppPie

First at all when you are creating delegate protocol it should conform to Class protocol. Like in example below.

protocol ProtocolDelegate: class {
    func myMethod(controller:ViewController, text:String)
}

Second, your delegate should be weak to avoid retain cycle.

class ViewController: UIViewController {
    weak var delegate: ProtocolDelegate?
}

Last, you're safe because your protocol is an optional value. That means its "nil" message will be not send to this property. It's similar to conditional statement with respondToselector in objC but here you have everything in one line:

if ([self.delegate respondsToSelector:@selector(myMethod:text:)]) {
    [self.delegate myMethod:self text:@"you Text"];
}

Above you have an obj-C example and below you have Swift example of how it looks.

delegate?.myMethod(self, text:"your Text")

Solution 5

Here's a gist I put together. I was wondering the same and this helped improve my understanding. Open this up in an Xcode Playground to see what's going on.

protocol YelpRequestDelegate {
    func getYelpData() -> AnyObject
    func processYelpData(data: NSData) -> NSData
}

class YelpAPI {
    var delegate: YelpRequestDelegate?

    func getData() {
        println("data being retrieved...")
        let data: AnyObject? = delegate?.getYelpData()
    }

    func processYelpData(data: NSData) {
        println("data being processed...")
        let data = delegate?.processYelpData(data)
    }
}

class Controller: YelpRequestDelegate {
    init() {
        var yelpAPI = YelpAPI()
        yelpAPI.delegate = self
        yelpAPI.getData()
    }
    func getYelpData() -> AnyObject {
        println("getYelpData called")
        return NSData()
    }
    func processYelpData(data: NSData) -> NSData {
        println("processYelpData called")
        return NSData()
    }
}

var controller = Controller()
Share:
171,745
Admin
Author by

Admin

Updated on July 08, 2022

Comments

  • Admin
    Admin almost 2 years

    How does one go about making a delegate, i.e. NSUserNotificationCenterDelegate in swift?

  • Shial
    Shial over 9 years
    Step2 shouldyn't be there weak reference to delegate ? if I'm I right please edit it. Btw you can make it optional value. That would be more swift. weak var delegate:FooTwoViewControllerDelegate? PS: delegate should be weak cus of retain circle, child shouldynt keep strong reference to parent
  • Shial
    Shial over 9 years
    In my way when you will make delegate optional you will resolve you unwraping error. delegate?.myVCDidFinish Becouse if delegate is not set the cod wont execute now :) In your version it will try to execute and will fail to unwrap if delegate is nil and you it is.
  • codingrhythm
    codingrhythm over 9 years
    you need to declare protocol like this in order to make weak reference possible for delegate protocol FooTwoViewControllerDelegate:class{}
  • Adrienne
    Adrienne about 9 years
    Love this. Very helpful
  • Faruk
    Faruk over 8 years
    @SeeMeCode Hi, It was good example firstly, but i still have an issue. How can i make my any UIViewController class to conform delegate we made? Are they have to be declared in one swift file? Any help will mean a lot.
  • SeeMeCode
    SeeMeCode over 8 years
    @Faruk It's been awhile since I posted this, but I think what you're asking should be pretty simple (If I'm misunderstanding, I apologize). Just add the delegate to your UIViewController after the colon. So something like class ViewController : UIViewController NameOfDelegate.
  • Faruk
    Faruk over 8 years
    @SeeMeCode yes, you got my question well. I tried your suggestion btw, but when I create a delegate class in a.swift according to your answer above, it doesn't come up in b.swift. I cannot reach any class outside of my swift file. any toughts?
  • Cing
    Cing over 8 years
    Could you please set by each step in which VC you are like VC1 and VC2. I am not really sure where to put them.
  • Suragch
    Suragch over 8 years
    I'm interested in learning more about this. Can you explain more about the terms you use: coupled, "avoid reuse the same protocol", "generic type-erasure". Why is abstracting it like this important? Should one always do this?
  • Robert
    Robert over 8 years
    @Shial - Actually it appears to be a little complicated. weak is only needed for classes not structs and enums. If the delegate is going to be a struct or enum then you don't need to worry about retain cycles. However, the delegate its a class (this is true for a lot of cases since quite often its a ViewController), then you need weak but you need to declare your protocol as a class. There is more info here stackoverflow.com/a/34566876/296446
  • Engineeroholic
    Engineeroholic over 8 years
    Finally someone that can explain protocol and delegate with common sense! thanks man!
  • Mahmud Ahmad
    Mahmud Ahmad almost 8 years
    What happens when you want to extend UIViewController, for example, in objective-c, you can have something lie this @interface MyCustomClass: UIViewController <ClassIWantToUseDelegate>, allowing you to init/configure the viewcontroller, as well as call delegate methods on the subviews? Something similar to this?
  • Marin
    Marin over 7 years
    What happens when Bossy Big Brother doesn't know he's a brother (Generics) ?
  • Suragch
    Suragch over 7 years
    @Marin, I'm not really sure that I understand your question. The list of rules (protocol) doesn't care who it is that is calling for the rules to be followed or who is following the rules. They are just rules.
  • Marin
    Marin over 7 years
    Basically I am referring to my question, slightly simplified over here. stackoverflow.com/questions/41195203/…
  • Marin
    Marin over 7 years
    Hi Adam, quick question, how can I set delegate = self, if I cannot instantiate an object because it is a generic class which I don't have access to in the other class, yet I want the generics class to call a function in the other class, hence the need for delegate?
  • mfaani
    mfaani over 7 years
    you're safe because your protocol is an optional value..... because you you use optional chaining delegate?.myMethod won't crash because if delegate is nil then nothing would happen. However if you made mistake and wrote delegate!.myMethod you could crash if a delegate is not set, so its basically a way for you to be safe...
  • Vaibhav Saran
    Vaibhav Saran almost 7 years
    on compiling above code it shows error Type 'ViewController' does not conform to protocol 'NetworkServiceDelegate' plz suggest. It is my 6th day on swift :)
  • Volodymyr
    Volodymyr about 6 years
    why do u use keyword "class" in the protocol description? what's the difference in using and not using it?
  • Bobby
    Bobby about 6 years
    The class keyword means it's a class only protocol. You can limit protocol adoption to class types, and not structures or enumerations, by adding the class keyword. I probably should not have added it to avoid any confusion, but since you asked I will keep.
  • iHarshil
    iHarshil about 6 years
    Your last 3 lines helped me to understand my scenario and solved my issue. Thanks Man! :)
  • Marin
    Marin over 5 years
    one thing i don't understand is why should I create a new instance of YelpApi just so that i call YelpApi's delegate ? What if the instance that's running is different from the 'new' one I just created... how does it know which delegate belongs to which instance of YelpApi ?
  • M Hamayun zeb
    M Hamayun zeb over 2 years
    Working For Men.....