is there any way to just replace a method name with another method name based on conditions in swift2.2?
example:
if(self.RecivedString == "varMethod"){
self.routes.varMethod(postData, andCompletionHandler: { (response, error) in
if(error.length == 0){
if(response.valueForKey("status") as! NSInteger == 1){
self.performSelectorOnMainThread(#selector(SubmitViewController.navigateToSubmissionViewController), withObject: nil, waitUntilDone: true)
}else{
self.showalert(response.valueForKey("msg") as! String)
}
}else{
self.showalert(error as String)
}
})
}
in the above example i want to replace self.routes.varMethod name with other self.routes.varMethodNew name base on conditions.
You cannot replace a method name with another method name , but you can have a closure variable to hold a reference to the methods.
Assuming you have two classes like this:
class Routes {
typealias CompletionHandler = ([String: AnyObject], NSError?)->Void
func varMethod(data: NSData, andCompletionHandler: CompletionHandler) {
//...
}
func varMethodNew(data: NSData, andCompletionHandler: CompletionHandler) {
//...
}
}
class SubmitViewController: UIViewController {
var routes: Routes = Routes()
var recievedString: String?
func showAlert(message: String) {/*...*/}
func navigateToSubmissionViewController() {/*...*/}
//...
}
You can write some method using the closure variable in your SubmitViewController
as:
func someMethod(postData: NSData) {
//Declare a closure variable
let theMethod: (NSData, andCompletionHandler: Routes.CompletionHandler)->Void //<-Make this match to `varMethod` and `varMethodNew`.
if self.recievedString == "varMethod" {
theMethod = self.routes.varMethod
} else {
theMethod = self.routes.varMethodNew
}
//And call it
theMethod(postData, andCompletionHandler: { response, error in
if error == nil {
if response["status"] as! Int == 1 {
dispatch_async(dispatch_get_main_queue()) {
self.navigateToSubmissionViewController()
}
} else {
self.showAlert(response["msg"] as! String)
}
} else {
self.showAlert(error!.localizedDescription)
}
})
}
But in your case, you can define the completion handler as a closure variable:
func someOtherMethod(postData: NSData) {
//Declare a closure variable
let completionHandler: Routes.CompletionHandler = { response, error in
if error == nil {
if response["status"] as! Int == 1 {
dispatch_async(dispatch_get_main_queue()) {
self.navigateToSubmissionViewController()
}
} else {
self.showAlert(response["msg"] as! String)
}
} else {
self.showAlert(error!.localizedDescription)
}
}
//And use it
if self.recievedString == "varMethod" {
self.routes.varMethod(postData, andCompletionHandler: completionHandler)
} else {
self.routes.varMethodNew(postData, andCompletionHandler: completionHandler)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.