如何将完成块传递给Swift中的另一个类

时间:2016-02-23 21:35:26

标签: swift block

在Objective-C中,我使用了一个完成块的处理,现在必须转换为Swift:

DetailDisplayController.h

中的

/Bower_Components/
DetailDisplayController.m

中的

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

@interface DetailDisplayController : UITableViewController

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

_rowChanged和_fetchedResultsController是实例变量

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

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

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

如何在Swift中执行此操作?

2 个答案:

答案 0 :(得分:3)

这里是你在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)

您可能希望仔细阅读Apple Swift文档的"Function Types""Closures"部分。

答案 1 :(得分:0)

在Swift中,补全真的很容易。这是一个例子。我按下按钮以打开SecondVC,然后按下SecondVC上的按钮将其关闭,然后调用完成操作,该操作将更改FirstVC上的标签:

    class ViewController: UIViewController {
    @IBOutlet weak var label: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func didTapButton(_ sender: Any) {
        let vc = storyboard?.instantiateViewController(withIdentifier: "SecondVC") as! SecondVC
        self.present(vc, animated: true, completion: nil)
        vc.completion = { str in
            self.label.text = str
        }
    }
 }

这是SecondVC的样子:

 class SecondVC: UIViewController {
    var completion:((String)->())?

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func didTapButton(_ sender: Any) {
        completion?("Hello")
        self.dismiss(animated: true, completion: nil)
    }
}