Enjoy Delegate & CallBack in Swift

Delegate and CallBack are mostly used techniques to pass the object around or Notify after the changes .

Delegate :

// HTTPClint.swift
// DelegateProtocol
// Copyright © 2016 googleDev. All rights reserved.
//
import Foundation
/*You need to specify class to be able to make the delegate reference weak. You make the delegate weak to avoid a strong retain cycle between the delegating and delegate objects.*/
protocol NetworkCall : class {
func downwloadData(data:String)
}
class HTTPClient {
weak var delegate:NetworkCall?
func DownloadData()
{
//AFNetwork Call and call the delegate to pass the object
delegate!.downloadData(“Data”)
}
}

View Model simply call HTTPCall message and notify the VM when the network complete the download by the delegate . HTTPCall will call the delegate when the download data is completed.

import Foundation
class NetworkVM: NetworkCall {
var httpCall = HTTPClient()
init() {
httpCall.delegate = self
httpCall.DownloadData()
}
func downloadData(data:String) {
print(“this is the data”)
}
}

CallBack(Closure)

import Foundation
class HttpUtilDownload {
func CallBackAfterDownload(url:String,completionHandler:(returnType:Bool) -> Void) {
//AFNETWORKING OR NSURLSESSION call
completionHandler(returnType: true)
}
}

After Download the data BOOL is return .Similarly we can send the data also.So VM get notified by the help of the callback .

import Foundation
class DetailVM {
var httpCall = HttpUtilDownload()
init()
{
httpCall.CallBackAfterDownload(“URL”) {
(result:Bool) in
print(result)
}
}
}
Show your support

Clapping shows how much you appreciated Shrawan K Sharma’s story.