你不能用另一个方法名替换一个方法名,但是你可以有一个闭包变量来保存对方法的引用。
假设你有两个这样的类:
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() {/*...*/}
//...
}
您可以使用SubmitViewController 中的闭包变量编写一些方法:
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)
}
})
}
但在您的情况下,您可以将完成处理程序定义为闭包变量:
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)
}
}