Ashish Agarwal
Ashish Agarwal

Reputation: 14925

Converting objective-c block to Swift closure

I am trying to convert this Objective-C block into Swift:

[self.client downloadEntity:@"Students" withParams: nil success:^(id response) {
      // execute code
}
failure:^(NSError *error) {
    // Execute code

}];

This is my code in Swift, but the syntax seems to be a bit off:

    client.downloadEntity("Students", withParams: nil, success:  {(students: [AnyObject]!) -> Void in
        print("here")
        },  failure:  { (error: NSError!) -> Void! in
            print ("here")
     }

This is giving me a few compilation errors:

  1. Value of 'AnyObject' has no member 'downloadEntity'
  2. It is complaining about the lack of commas (,) right after the failure part of the code

Upvotes: 3

Views: 392

Answers (2)

Ciprian C
Ciprian C

Reputation: 247

Try this:

client.downloadEntity("Student", withParams: nil,
        success: { (responseObj) -> Void in
            print("success: \(responseObj)")
        },

        failure: { (errorObj) -> Void in
            print("treat here (in this block) the error! error:\(errorObj)")
        })

Upvotes: 3

Mr Beardsley
Mr Beardsley

Reputation: 3863

You need to switch to the new Swift error syntax, and you can also using trailing closures. I had to use a bool for the example to show how you would call your success closure, or you would throw an error.

var wasSuccessful = true // This is just here so this compiles and runs

// This is a custom error type. If you are using something that throws an
// NSError, you don't need this.
enum Error:ErrorType {
    case DownloadFailed
}

// Hopefully you have control over this method and you can update
// the signature and body to something similar to this:
func downloadEntity(entityName: String, success: ([AnyObject]) -> Void)  throws {
    let students = [AnyObject]()

    // download your entity
    if wasSuccessful {
        // Call your success completion handler
        success(students)
    }
    else {
        throw Error.DownloadFailed
    }
}

When you have a function that can throw an error, you need to call it with try inside a do/catch block.

// Calling a function that can throw
do {
    try downloadEntity("Students") { students in 
        print("Download Succeded")
    }
}
catch Error.DownloadFailed {
    print("Download Failed")
}
// If you are handling NSError use this block instead of the one above
// catch let error as NSError {
//     print(error.description)
// }

Upvotes: 2

Related Questions