sajaz sajaz - 1 year ago 81
Swift Question

How to inherit a function with closure in Swift

I have define this function in my APIServices class

typealias APIResponseOK = (data:NSDictionary, extra:NSDictionary) -> Void
typealias APIResponseError = (failure:Bool, code:NSString, message:NSString) -> Void

func getHttp(action:NSString, onResult:APIResponseOK, onError:APIResponseError) -> Void {

let strUrlRequst = String(format: "\(action)")

Alamofire.request(.GET, strUrlRequst).responseJSON { (responseData) -> Void in

if(responseData.result.error == nil){

if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)

print("Response \(swiftyJsonVar)")

onResult(data: swiftyJsonVar.dictionaryObject!, extra: swiftyJsonVar.dictionaryObject!);
onError(failure: true, code: "OM_ERR", message: (responseData.result.error?.localizedDescription)!);


Now I want to inherit this function in ViewController class. What I tried is as bellow.

apiServices.getHttp("Somename", onResult: (data:NSDictionary, extra:NSDictionary){

onError:(failure: Bool, code:NSString, message:NSString){


Why i get this error. Please correct me, I am very much new to swift

enter image description here

Answer Source

Correct your function declaration :

func getHttp(action:NSString, onResult:APIResponseOK, onError:APIResponseError) -> Void {


func getHttp(action:NSString, onResult:APIResponseOK, onError:APIResponseError) {

After that , to call this function you can do:

let myApiSuccess: APIResponseOK = {(data:NSDictionary?, extra:NSDictionary?) -> Void in
    print ("Api Success : result is:\n \(data)")
    // Here you can make whatever you want with your dictionaries

let myApiFailure: APIResponseError = {(failure:Bool?, code:NSString?, message:NSString?) -> Void in
    print ("Api Failure : error is:\n \(message)")
    // Here you can check the errors with your vars looking for failure, code and message

getHttp(action:NSString, onResult:APIResponseOK, onError:APIResponseError)

You can find more details in this SO answer

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download