如何在 swift 中使用 block/closure

How to use block/closure in swift

在我的一个应用程序中,我使用块来调用 Web 服务并获得响应。现在我想在 swift 中编写此应用程序,但在 Swift 中使用 blocks/Closure 时遇到了麻烦。 这是我要在 swift 中迁移的 objective C 代码:

调用 Communicator 的 class 方法

[[Communicator sharedInstance]callWebService:WS_LOGIN withMethod:POST_METHOD andParams:params showLoader:YES completionBlockSuccess:^(id obj) {
   //Do play with data
}completionBlockFailiure:^(id obj) {
   //Show alert with error
}];

在通讯器中class

-(void)callWebService:(NSString *)serviceName withMethod:(NSString *)methodName andParams:(NSDictionary *)params showLoader:(BOOL)showLoader completionBlockSuccess:(void (^)(id))aBlock completionBlockFailiure:(void (^)(id))aFailBlock
{
   if (showLoader) {
   // show loader
   }
   [self performRequestWithServiceName:serviceName method:methodName andParams:params successblock:aBlock failureblock:aFailBlock];
}

- (void)performRequestWithServiceName:(NSString *)serviceName method:(NSString*)methodName andParams:(NSDictionary*)params
                 successblock:(void (^)(id obj))successBlock
                 failureblock:(void (^)(id obj))failBlock {
   if(callSuceess){
      successBlock(@"Success");
   }else{
      successBlock(nil);
   }
}

对于Swift Closures我们必须使用( ) -> ( )

例如:

func yourFunction(success: (response: AnyObject!) -> Void, failure: (error: NSError?) -> Void) {

}

您可以这样称呼它:

yourFunction({(response) -> Void in
    // Success
}) { (error) -> Void in
    // Handle Errors
}

希望它能帮助您创建符合您要求的闭包。

对于 Swift。使用 AnyObject 作为 id objc 类型。

func callWebservice (serviceName: String, withMethod method: String, andParams params: NSDictionary, showLoader loader: Bool, completionBlockSuccess aBlock: ((AnyObject) -> Void), andFailureBlock failBlock: ((AnyObject) -> Void)) {
    if loader {
        // Show loader
    }

    performRequestWithServiceName(serviceName, method: method, andParams: params, success: aBlock, failure: failBlock)
}

func performRequestWithServiceName(serviceName: String, method methodName: String, andParams params: NSDictionary, success successBlock: ((AnyObject) -> Void), failure failureBlock: ((AnyObject) -> Void)) {
    if callSuceess {
        successBlock("Success")
    }else {
        successBlock(nil)
    }
}

更新:您想要调用 web service 时的示例。请参阅下面的代码

callWebservice("your-service-name", withMethod: "your-method", andParams: ["your-dic-key": "your dict value"], showLoader: true/*or false*/, completionBlockSuccess: { (success) -> Void in
    // your successful handle
}) { (failure) -> Void in
    // your failure handle
}

您的代码可能如下所示:

func callWebService(serviceName: String, method: String, params: [String : AnyObject], showLoader: Bool, success: (responseObject: AnyObject) -> Void, failure: (responseObject: AnyObject) -> Void) {
    if showLoader {
        // show loader
    }

    performRequest(serviceName, method: method, params: params, success: success, failure: failure)
}

func performRequest(serviceName: String, method: String, params: [String : AnyObject], success: (responseObject: AnyObject) -> Void, failure: (responseObject: AnyObject) -> Void) {

}

我用 [String : AnyObject] 替换了 NSDictionary。如果您可以将 AnyObject 的任何用法替换为更具体的类型,您的代码将更加清晰和稳定。

在 communicator class 中,调用 web 服务的方法将定义为类似这样的内容,具体取决于您要访问的对象类型 return

func performRequest(serviceName: NSString, methodName: NSString,paramaters:NSDictionary, successblock: (String)->(), failureBlock: () -> ()) {
    if(callSuccess) {
        successblock("Success")
    } else {
       failureBlock() 
}

我们通过它们的函数签名来定义成功和失败的块类型,在上面的例子中,成功被定义为一个方法,它接受一个字符串作为输入参数,return什么都没有,所以我们可以调用 successBlock传入一个字符串。失败块在上面定义为不带参数且return什么都没有的块。

调用此方法

func callWebService(serviceName: NSString, method: NSString and parameters: NSDictionary, showLoader: Bool, completionBlockSuccess:(String) -> (), completionBlockFailiure:() -> ()) {
    if (showLoader) {
    // show loader
    }
    performRequest(serviceName: serviceName, methodName: method, parameters, successBlock:completionBlockSuccess, failureBlock: completionBlockFailiure)
}

终于要调用这个了

Communicator.sharedInstance().callWebService(serviceName: WS_LOGIN , method: POST_METHOD and parameters: params, showLoader: true, completionBlockSuccess:{ returnedString in

     //Do play with data

}, completionBlockFailiure:{ 

    //Show alert with error

})

对于完成块,我们定义了一个变量 returnedString 以允许我们操作该输入参数(在上面的示例中它将是字符串 "Success")。我假设你的数据不仅仅是 returning 一个字符串,所以你可能需要根据你的服务 returns.

来处理它们的类型

同样在这里,我尝试使用 NSString 和 NSDictionary 来匹配您的方法签名,但根据您的需要,Swift 等价物 String 和 [String: AnyObject] 可能更合适。

func processingWithAnyObject(input: String, completion: @escaping (_ result: AnyObject) -> Void) {
    ...
    completion(response.result.value! as AnyObject)
}

processingWithAnyObject("inputString") {
    (result: AnyObject) in
    print("back to caller: \(result)")
}