Given this piece of code in ObjC that is used by an app, I want to convert it to Swift:
typedef void (^VoidBlock)(void);
@interface Worker : NSObject
- (void)add:(VoidBlock)completion;
- (void)remove:(VoidBlock)completion;
- (void)execute;
@end
@implementation Worker {
NSMutableArray<VoidBlock> *completions;
}
- (void)add:(VoidBlock)completion {
[completions addObject:completion];
}
- (void)remove:(VoidBlock)completion {
[completions removeObject:completion];
}
- (void)execute {
// ...
[completions enumerateObjectsUsingBlock:^(VoidBlock _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
obj();
}];
}
@end
I have problems when implementing remove. I tried several things, but nothing. Basically, I cannot compare closures in Swift because evidently closures don't conform to Equatable protocol, so, it cannot be found in the array. Perhaps the memory address can be used for this, I don't know if there is a problem between objc pointer and swift references. In theory, this code could be used from objc or swift. Another idea I had was to use something like:
let firstIndex = hardWorkers.firstIndex(where:{
$0 === hardWorkerClosure
})
Note the identity operator, but that does not work. A friend told me that perhaps I had to use a container for the closure/block. I remember in Objc we have NSValue to wrap a primitive type inside a class, so, we can save them inside NSMutableArray, but I don't remember anything to save blocks. Do you have any idea or suggestion about how to solve this problem? Thanks a lot.