Codementor Events

How to Create Delegates in Swift

Published Nov 16, 2016Last updated Jan 18, 2017
How to Create Delegates in Swift

What are delegates?

Delegates are the objects which allow one object to send a message as events happen. If you are not a beginner, then you are fully aware of the delegate pattern used in iOS app development. If you are a beginner and did not understand the definition written at the beginning of this tutorial, don't worry, I will explain it in simple terms with real time scenario/example. Similarly, here's a getting-started guide in Swift, in case you need more background information.

Suppose you have to view controllers VC1 and VC2; and currently, the user is on VC1 then navigated to VC2. In VC2, the user selected something and we have to display the selected item on VC1. This can be achieved using delegates as it will send a message to VC1 when the user selects something in VC2.

How to create delegates

Syntax:

protocol delegateName: class {
    func delegate function name() 
}

We created a class-based delegate because in Swift, we can only create a weak reference to delegate an object if it's created as class-based.

Example:

protocol AACalendarDelegate: class {
    func dateSelected(date: NSDate)
}

In the example above, we created the delegate for our VC2 class. This allows the user to notify the VC1 which implements it to receive the date selected by the user. When the user selects the date, we will fire the dateSelected delegate function and it triggers the function implementation in VC1.

Now it's time to create the delegate property so that it can be accessible through VC1 class. The complete code of VC2 class will look something like this:

protocol AACalendarDelegate: class {
    func dateSelected(date: NSDate)
}

class VC2 : UIView {
  weak var delegate:AACalendarDelegate? 
}

Force delgate to notify VC1:

func doneWithDateSelection() {
        self.delegate?.dateSelected(NSDate(timeIntervalSinceNow: 0))
    }

In the code above, we force our delegate to call the dateSelected function so that the VC1 class will get notified. This is important in order to make the VC1 class receive the event that user has selected some dates in the VC2 class.

For more on how to conform the VC1 class to AACalendarDelegate, check out the link below:

http://stackoverflow.com/questions/24099230/delegates-in-swift here

Discover and read more posts from Aman Aggarwal
get started
post commentsBe the first to share your opinion
Show more replies