Delegates in Swift

Delegates in Swift are pretty cool. They work sorta like how inheritance works except that the actions a delegate can carry out are scoped rather than a default inheritance of all attributes or capabilities of the delegator.

One analogy is the President having a delegate to the UN. The delegate can carry out a set of actions on behalf of the President, but can’t really do everything the President can. A delegate is not an instance of what it represents.

The official Apple docs describes Delegation as “a design pattern that enables a class or structure to hand off (or delegate) some of its responsibilities to an instance of another type.”  One such a example is AVAudioRecorder , where a class that uses its instance to record audio can’t tell when it is done recording unless it’s a delegate.

AVAudioRecorder  uses a protocol to define what a delegate can know and do. As the source code shows below

public protocol AVAudioRecorderDelegate : NSObjectProtocol {

    optional public func audioRecorderDidFinishRecording(recorder: AVAudioRecorder, successfully flag: Bool)

    optional public func audioRecorderEncodeErrorDidOccur(recorder: AVAudioRecorder, error: NSError?) … 

}

By simply specifying my controllerView as a delegate I can now tell when recording is done

class RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate {

    var audioRecorder:AVAudioRecorder! ….

    try! audioRecorder = AVAudioRecorder(URL: filePath!, settings: [:])

    audioRecorder.delegate = self

    func audioRecorderDidFinishRecording(recorder: AVAudioRecorder, successfully flag: Bool) {

        <#code#>

    }

}

Now your instance of one class type can carry out activities and responsibilities of another class. You go Delegate!

see more:

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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

Blog at WordPress.com.

Up ↑

%d bloggers like this: