I'm working on converting this In-App Purchase tutorial into Swift and have come across an issue trying to save the completion handler. We need to store this completion handler so that it can be called later. I cannot figure out how to store a copy of the closure from the arguments. Specifically, I believe I need to copy it but Xcode states this object doesn't have a copy function.
I've defined it like so:
typealias RequestProductsCompletionHandler = (success: Bool, products: NSArray) -> Void
Here I declare a property for it:
var completionHandler: RequestProductsCompletionHandler?
Then this is where I need to store the passed in completion handler into my property:
func requestProductsWithCompletionHandler(completionBlock: RequestProductsCompletionHandler) -> Void {
//self.completionHandler = completionBlock.copy() //problem: RequestProductsCompletionHandler does not have a member named copy
}
This is how it was done in the Obj-C tutorial:
typedef void (^RequestProductsCompletionHandler)(BOOL success, NSArray * products);
RequestProductsCompletionHandler _completionHandler;
- (void)requestProductsWithCompletionHandler:(RequestProductsCompletionHandler)completionHandler {
_completionHandler = [completionHandler copy];
}
And later it is used like so:
_completionHandler(YES, skProducts);
_completionHandler = nil;
EDIT: I've removed the .copy() to prevent the error (also had to make the NSArray optional so that I can set it to nil later). My question is, will it work as expected without explicitly copying it? I don't believe it will because Apple stated closures are reference types. This will store a reference to the original closure which I don't want to do. How does one enforce a copy?