2016-05-12 83 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

啊看起來像)謝謝 –