2016-05-12 73 views
0

我想创建一个像这段代码一样完成的函数。所以函数应该得到一个message和一个完成块。在Swift中用闭包声明函数

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 

我想斯威夫特同样的功能,以及如何实际处理该块。

回答

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")!) 
} 
+0

啊看起来像)谢谢 –