在Swift中声明闭包函数

时间:2016-05-12 12:34:28

标签: swift swift2 swift2.2

我想在此代码中创建一个完成的函数。因此该函数应该得到一个message和一个完成块。

QMServicesManager.instance().chatService.chatAttachmentService.getImageForAttachmentMessage(message, completion: {
              [weak self] (error: NSError?, image: UIImage?) -> Void in

              guard attachmentCell.attachmentID == attachment.ID else {
                return
              }

              self?.attachmentCellsMap.removeObjectForKey(attachment.ID)

              guard error == nil else {
                // TODO - ui. show error later
                //SVProgressHUD.showErrorWithStatus(error!.localizedDescription)
                print("Error downloading image from server: \(error).localizedDescription")
                return
              }

              if image == nil {
                print("Image is nil")
              }

              attachmentCell.setAttachmentImage(image)
              cell.updateConstraints()

              })
          }

在objective-c中,它简单地声明为:

- (void)getImageForAttachmentMessage:(QBChatMessage *)attachmentMessage completion:(void(^)(NSError *error, UIImage *image))completion

我想在Swift中使用相同的函数以及如何实际处理这个块。

1 个答案:

答案 0 :(得分:1)

保持精确,我想你想要这样:

func getImageForAttachmentMessage(attachmentMessage : QBChatMessage, completion: (error: NSError?, image: UIImage) -> Void) -> Void{
    //code goes here
    let error = NSError(domain: "domain", code: 1, userInfo: nil)
    completion(error: error, image: UIImage(named: "sample")!)
}