Ulli H
Ulli H

Reputation: 1878

How to pass a completion block to another class in Swift

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

in DetailDisplayController.h

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

@interface DetailDisplayController : UITableViewController

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

in 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 and _fetchedResultsController are instance-variables

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)
           ...

How can I do this in Swift?

Upvotes: 2

Views: 5619

Answers (2)

Dinu Nicolae
Dinu Nicolae

Reputation: 1281

In Swift completions are really easy. Here is an example. I press the button to open a SecondVC and then I press a button on the SecondVC to close it and I call a completion which is going to change a label on the 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
        }
    }
 }

and this is what the SecondVC looks like:

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

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

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

Upvotes: 0

Ewan Mellor
Ewan Mellor

Reputation: 6847

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)

You probably want to have a good read of the "Function Types" and "Closures" sections of the Apple Swift docs.

Upvotes: 8

Related Questions