krisacorn
krisacorn

Reputation: 831

How do I use a completionBlock in swift?

I'm trying to utilize swift's SKStoreProductViewController, but am getting errors with my syntax, specifically with my completion block.

Here is my code:

let storeViewController:SKStoreProductViewController = SKStoreProductViewController();
storeViewController.delegate = self;

var productparameters = [SKStoreProductParameterITunesItemIdentifier:someitunesid];

storeViewController.loadProductWithParameters(productparameters,
    (success: Bool!, error: NSError!) -> Void in
        if success {
    self.presentViewController(storeViewController, animated: true, completion: nil);
        } else {
        NSLog("%@", error)
    }
  )

After running this I get an expected "," separator error between the error:NSError!),-> Void

This doesn't make sense to me as the apple docs call for:

func loadProductWithParameters(_ parameters: [NSObject : AnyObject]!,
           completionBlock block: ((Bool, NSError!) -> Void)!)

What am I doing wrong?

Upvotes: 4

Views: 3735

Answers (1)

Nate Cook
Nate Cook

Reputation: 93276

You're 99% there, you just need braces around your block to have the correct closure syntax:

storeViewController.loadProductWithParameters(productparameters, { (success: Bool!, error: NSError!) -> Void in
    if success {
        self.presentViewController(storeViewController, animated: true, completion: nil);
    } else {
        NSLog("%@", error)
    }
})

You can read more about closures in Apple's documentation.

Upvotes: 3

Related Questions