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:
Leave a Reply