如何在Swift中将完成块传递给另一个类 [英] How to pass a completion block to another class in Swift

查看:132
本文介绍了如何在Swift中将完成块传递给另一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中,我使用了对完成块的这种处理,现在必须将其转换为Swift:

In Objective-C, I used this handling of a completion-block that now must be transformed to Swift:

DetailDisplayController.h

typedef void (^AddedCompletitionBlock)(BOOL saved, NSString *primarykey, NSUInteger recordCount);

@interface DetailDisplayController : UITableViewController

@property (nonatomic, copy) AddedCompletitionBlock completionBlock;
@property (strong, nonatomic) Details *detail;

DetailDisplayController.m

- (void) saveClicked:(id)sender
{  
   // retrieve PK
   NSString *objectId = [[[_detail objectID] URIRepresentation] absoluteString];

   if (self.completionBlock != nil)
   {
       self.completionBlock(_rowChanged, objectId, [_fetchedResultsController.fetchedObjects count]);
   }

_rowChanged和_fetchedResultsController是实例变量

_rowChanged and _fetchedResultsController are instance-variables

,并且在调用类的 DetailViewController.m 中,使用了传递的块

and in DetailViewController.m a the calling class, the passed block is used

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
   if ([segue.identifier isEqualToString:@"DetailDisplay"])
   {
       DetailDisplayController *detailDisplayController = segue.destinationViewController; 
       ...
       detailDisplayController.completionBlock = ^(BOOL saved, NSString *sorter, NSUInteger recordCount)
       {
        if (saved)
           ...

如何在Swift中执行此操作?

How can I do this in Swift?

推荐答案

以下是您在Swift中所需的等效组件:

Here's the equivalent pieces that you need in Swift:

typealias AddedCompletionBlock = (saved: Bool, primaryKey: String, recordCount: Int) -> Void

var completionBlock: AddedCompletionBlock? = nil

completionBlock = {saved, primaryKey, recordCount in
    print("\(saved), \(primaryKey), \(recordCount)")
}

completionBlock?(saved: true, primaryKey: "key", recordCount: 1)

您可能希望对部分.

这篇关于如何在Swift中将完成块传递给另一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆