UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Some help with delegate pattern, kindly guide

Forums > Swift

I was working on delegate pattern and unable to grasp my mind around it, So here is what i am thinking

I create a protocol - basically what i want to do but not defining how

protocol PrintWords: AnyObject {
    func printWords()
}

I create a worker class/struct - this creates a reference to protocol, create a function and call the protocol method inside its own mehtod

class printWorker {
    weak var delegate: PrintWords?
    func playNow() {
        delegate?.printWords()
    }
}

then in another class , create a reference to this worker class/struct, adopt. the protocol, then implement its method

class TestProtocol: PrintWords {
 private let worker = printWorker()
    init() {
        worker.delegate = self
    }

    func printWords() {
        print("Good job")
    }
}

but i do not understand why i am creating the worker class/struct printWorker, can i just not adopt a protocl and implement its method in TestProtocol? also i do not use the playNow() function any where , what is its use, can any one please explain, thanks.

2      

can i just not adopt a protocl and implement its method in TestProtocol?

Yes, you can. In Paul's UIKit stuff, he frequently does this with delegates such as UITableViewDataSource, where he does something like this:

class MyTableView: UICollectionViewController {
    override func viewDidLoad() {
        //view loading stuff

        //set the delegate to ourself since we conform
        //to the UITableViewDataSource protocol
        // (see below)
        delegate = self
    }
}

//conform MyTableView to the UITableViewDataSource protocol
extension MyTableView: UITableViewDataSource {
    //implament the required UITableViewDataSource methods
}

(And I apologize for any minor mistakes in the above code; I did it all from memory without bothering to check anything and it's been a while since I did any UIKit work.)

3      

@roosterboy - i was reading the definition of delegation from apple documents, can you please tell me what is the delegate object and delegating object in my sample code, if there is any ? Thanks

Delegation is a simple and powerful pattern in which one object in a program acts on behalf of, or in coordination with, another object. The delegating object keeps a reference to the other object—the delegate—and at the appropriate time sends a message to it. The message informs the delegate of an event that the delegating object is about to handle or has just handled. The delegate may respond to the message by updating the appearance or state of itself or other objects in the application, and in some cases it can return a value that affects how an impending event is handled. The main value of delegation is that it allows you to easily customize the behavior of several objects in one central object.

2      

So after studying some more material , i understand this much

I create a protocol with some functionality

protocol DisplayNameDelegate { 
    func displayName(name: String) 
}

I then create a struct or class that uses or calls the methods of the protocol and provides the data for the methods in protocol.

struct Person  { 
    var displayNameDelegate: DisplayNameDelegate

    var firstName = "" { 
        didSet { 
            displayNameDelegate.displayName(name: getFullName()) 
        } 
    } 
    var lastName =  "" { 
        didSet { 
            displayNameDelegate.displayName(name: getFullName()) 
        } 
    } 

    init(displayNameDelegate: DisplayNameDelegate) { 
        self.displayNameDelegate = displayNameDelegate 
    } 

    func getFullName() -> String { 
        return "\(firstName) \(lastName)" 
    } 
}

then if any struct/class adheres to the protocol , that type has to now declare all the methods in the protocol and assign values in the initialiser if possible ...

struct MyDisplayNameDelegate: DisplayNameDelegate { 
    func displayName(name: String)  { 
        print("Name: \(name)") 
    } 
}  

But what after this... so i have a struct/class that now says i will do the work of defining the functions in protocol, then in the class/struct where say if a button is clicked , then a function is called that in turn uses a function in protocol ...

That in turn invokes the struct/class that adopts the protocol and makes it run...

var displayDelegate = MyDisplayNameDelegate()
var person = Person(displayNameDelegate: displayDelegate) 
person.firstName = "Al"  
person.lastName = "Pacino" 

Is that what delegate model is ? Please guide ...

Code credit = Ivan Morgan

2      

For further explanation of the delegate pattern this is a good video: https://www.youtube.com/watch?v=DBWu6TnhLeY

2      

@Hatsushira - i saw it earlier , but i totally get lost in the back and forth between views , and delegate here , delegate there , i really need to know what this pattern tries to achieve , can you suggest for eg what is UITableView , is it like a Person class in above example ...also what is UIViewController in context of above example , thanks

2      

This depends what you want to achieve. From what I read and what you provided as code example here you want to create a protocol which enables any struct/class which implements it to be able to print. Then you don't need a delegate for this.

It would be sufficient to write:

struct Person: PrintWords {
  func displayName(name: String)  { 
        print("Name: \(name)") 
    }
}

or

extension Person: PrintWords {
  func displayName(name: String)  { 
        print("Name: \(name)") 
    }
}

Unless I completely misunderstood what you're trying to achieve.

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.