2

i am on macOS, objective-c. I included a Swift 5 framework and one thing i don't know is how to provide a closure.

This is the swift declaration:

var cancelledStateColorHandler: ((NSColor) -> NSColor)?

How do i pass a handler from objective-c to return an NSColor?

Pat_Morita
  • 3,355
  • 3
  • 25
  • 36
  • 1
    In Objective-C, they are called `block`. http://fuckingblocksyntax.com https://stackoverflow.com/questions/42647453/best-practice-to-declare-objective-c-blocks-as-variable etc. – Larme Nov 13 '20 at 09:54
  • I know that. The question is how to pass them to the above SWIFT declared variable from objective-c – Pat_Morita Nov 13 '20 at 10:15
  • 1
    `yourInstance.cancelledStateColorHandler = ^NSColor * _Nonnull(NSColor * _Nonnull input) { if ([input isEqual:[UIColor whiteColor]]) { return [NSColor redColor]; } else { return NSColor.redColor; } };`? I don't understand your issue. – Larme Nov 13 '20 at 10:35
  • that solved it - i just didn't know about the correct syntax, please make it an answer so i can accept it (and change UIColor to NSColor for the sake of correctness) – Pat_Morita Nov 13 '20 at 15:31

1 Answers1

1

According to F*ck*ngBlockSyntax, we write a block as a var that way:

returnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};

var cancelledStateColorHandler: ((NSColor) -> NSColor)? would translated into swift as @property (nonatomic, copy) NSColor * _Nonnull (^ _Nullable cancelledStateColorHandler)(NSColor * _Nonnull);. To simulate it, check your Project-Swift.h file.

I tested with

@objc class TestClass: NSObject {
    @objc
    var cancelledStateColorHandler: ((NSColor) -> NSColor)?
}

And got:

SWIFT_CLASS("_TtC10ProjectName9TestClass")
@interface TestClass : NSObject
@property (nonatomic, copy) NSColor * _Nonnull (^ _Nullable cancelledStateColorHandler)(NSColor * _Nonnull);
- (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
@end

Now, we only focus on the second part of the syntax, since the left part, is yourInstance.cancelledStateColorHandler

^returnType         (parameters              ) {...};
^NSColor * _Nonnull (NSColor * _Nonnull input) {...};

So we got:

yourInstance.cancelledStateColorHandler = ^NSColor * _Nonnull(NSColor * _Nonnull input) { 
    //Here that's sample code to show that we can use the input param, and that we need to return a value too.
    if ([input isEqual:[NSColor whiteColor]]) 
    { 
        return [NSColor redColor]; 
    } 
    else 
    { 
        return NSColor.redColor;
    }
};
Larme
  • 24,190
  • 6
  • 51
  • 81