Where to set delegate in swift?

swift delegate
swift set delegate to another class
what's a delegate in swift
set delegate programmatically swift
delegate in ios
difference between delegate and protocol in swift
what is delegate and datasource in swift
custom delegate in swift - stack overflow

I've set up a simple Swift project to try and wrap my head around delegates & protocols. The goal is to pass data between two classes (SendingClass & ReceivingClass). Two buttons in the SendingClass are linked to the delegate which should trigger the Protocol conforming function in the ReceivingClass to execute. This doesn't work unfortunately, I suspect it has to do with where and how I am declaring the ReceivingClass as the delegate.

Appreciate your insights, i'm just starting out!

I've tried setting the delegate in various locations (presently within viewDidLoad, but cant get it to work).

let vc = SendingClass()
vc.statusDelegate = self


import UIKit

protocol StatusDelegate {
    func statusChanged(state: Bool, sender: String)

class SendingClass: UIViewController {

    var statusDelegate : StatusDelegate?

    @IBAction func button1Pressed(_ sender: UIButton) {
      statusDelegate?.statusChanged(state: true, sender: "Button 1")

    @IBAction func button2Pressed(_ sender: UIButton) {
        statusDelegate?.statusChanged(state: false, sender: "Button 2")



import Foundation
import UIKit

class ReceivingClass: UIViewController, StatusDelegate {

    override func viewDidLoad() {
        let vc = SendingClass()
        vc.statusDelegate = self

    func statusChanged(state: Bool, sender: String) {
        print("Sender = \(sender) , State = \(state)")

Expected: the ReceivingClass protocol conforming function (func statusChanged) should execute each time the buttons are pressed within the SendingClass.

Actual: Nothing happens

I am using this..
// create extension in your receiving class
extension ReceivingClass: PopUpVCDelegate {
   func statusChanged(state: Bool, sender: String) {
        print("Sender = \(sender) , State = \(state)")

// on sending class, when you present your receiving class on any button click
let resultController = self.storyboard?.instantiateViewController(withIdentifier: "PopUpVCID") as? PopUpVC       

        resultController?.delegate = self
  self.present(resultController!, animated: true, completion: nil)

 //or if not have button add on viewdidload in receiving class

// here is full eg

How to get data from popup view controller to custom table view cell?

Quick Guide to Swift Delegates, Key Steps to Delegation. Create a delegate protocol that defines the messages sent to the delegate. Create a delegate property in the delegating class to keep track of the delegate. Adopt and implement the delegate protocol in the delegate class. Call the delegate from the delegating object. The basic steps to use delegation are the same for both Objective-C and Swift: Create a delegate protocol that defines the messages sent to the delegate. Create a delegate property in the delegating class to keep track of the delegate. Adopt and implement the delegate protocol in the delegate class. Call the delegate from the delegating object.

For protocol and delegate, you use it when u want to bring a value from 2nd VC (presented by 1st or pushed by 1st VC) to 1st VC, which is the original. From your code, I dont see you presenting or pushing your 2nd VC. that's why it's not working. Hopefully I answered your doubt.

However if you still want to bring a value over from 1st VC to 2nd VC. In second VC, create a variable to receive it

var ReceivedData = String()

then from your first VC, when u are going to push it,

let vc = SendingClass()
vc.ReceivedData = "Whatever you want it to receive"

Implementing delegates in Swift, step by step., For a better explanation, I am going to show you how to create a custom delegate that passes data between classes, with Swift in a simple� ViewController includes a UICollectionView instance (call it collectionView). You set the collectionView instance’s delegate property to self and self is ViewController. ViewController adopts the UICollectionViewDelegate protocol. The delegate is ViewController.

If you're using storyboard segues, maybe the view controller is instantiated from there so probably you have to use the prepareForSegue and get the destination view controller (which is already instantiated for you) in the ReceivingClass view controller:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    super.prepare(for: segue, sender: sender)

    if let destination = segue.destination as? SendingClass {
        destination.delegate = self

Also be careful with delegate patter: the delegate property should be declared as a weak property to avoid retain-cycle

weak var delegate: MyDelegate?

How to Create Delegate in Swift. In class that send the data create , “How to Create Delegate in Swift” is published by Alexander Deplov. class BackButton: SKNode {var delegate: BackButtonActionDelegate? The delegate pattern has long been very prominent on Apple's platforms, and used for everything from handling table view events using UITableViewDelegate, to modifying cache behavior using NSCacheDelegate. This week, let's take a look at a few ways to implement the delegate pattern, along with their pros and cons.

Understanding Delegates and Delegation in Swift 4, You set the collectionView instance's delegate property to self and self is ViewController . ViewController adopts the UICollectionViewDelegate� Use Swift’s extensions to separate your code, giving each set of delegate functions its own extension. Abstract away multiple delegate functions into one controller (or “manager”) and use closures to respond to the fine-grained data you actually need.

Delegation In Swift Explained (How To) – LearnAppMaking, The Bakery class has a function called makeCookie() that creates a cookie with the Cookie struct, and sets some of its properties. A this point we� To resolve this, simply downcast to "AppDelegate" or what ever your UIApplication subclass happens to be called. In Swift 3, 4 & 5, this is done as follows: let appDelegate = UIApplication.shared.delegate as! AppDelegate let aVariable = appDelegate.someVariable

Delegation in Swift, Just like how UITableView has a UITableViewDelegate protocol, we can also setup our own types in a similar fashion - like how we here define� Firstly take a look at life cycle of the view. Depending on this it is possible to highlight that method awakeFromNib is quite suitable because:. The nib-loading infrastructure sends an awakeFromNib message to each object recreated from a nib archive, but only after all the objects in the archive have been loaded and initialized.

  • How do you present your SendingClass? From the IBActions, I guess you do it from a storyboard.
  • Where do you present SendingClass?
  • @ Dávid Pásztor, @Rico Crescenzio Yes the buttons are presented through a simple story board. I've tested the IBactions with print statements and they seem to work fine.
  • @GCr has my answer helped you?
  • OK, so the protocol / delegate pattern is reserved for managing the presentation of views on the stack? Would it be appropriate to use this pattern if the ReceivingClass is in fact the model, and not a ViewController. So the ReceivingClass is just listening for changes in the SendingClass and then responding (but not being presented).
  • erm..didnt really get your question...And pls do upvote any answers around that helped..New members like me especially..haha