Search code examples
objective-cswiftfunctionclassobjc-bridging-header

Access Swift function for an object from Objective-C class


I'm trying to implement some Swift-framework into my Objective-C project. I have already set up all Bridge-Headers and also written @objc before functions and classes in a swift class. So it's required to do the following, but the example code is given in Swift:

barView.addBarBackground(startAngle: 90, endAngle: -270, radius: 100, width: 15)

I have to perform this code in Obj-c class for an object barView. I tried to do this, but it doesn't work:

[_barView.addBarBackground startAngle: 90 endAngle: -270 radius: 100 width: 15];

What should I do?

EDIT:

I have a IBOutlet connection:

@property (strong) IBOutlet OGCircularBarView *barView;

So, there is an object named barView. I also have some Swift-class with the code:

import Cocoa

@objc public class OGCircularBarView: NSView, Sequence {
     //...
     @objc public func addBarBackground(startAngle: CGFloat, endAngle: CGFloat, radius: CGFloat, width: CGFloat, color: NSColor) {
        //some code
     }
     //...
}

I need to perform that code (which is given in Swift) in an Objective-C class:

barView.addBarBackground(startAngle: 90, endAngle: -270, radius: 100, width: 15)

How can I rewrite it so that it works in Objective-C?


Solution

  • Try this:

    [_barView addBarBackgroundStartAngle: 90 endAngle: -270 radius: 100 width: 15];
    

    The first problem is that you can't use dot syntax for methods; that's what the brackets are for: [object message:withArguments:...]

    The second is that the Swift function name is a bit awkward for Obj-C translation. If you declare the swift function as follows:

    func addBarBackgroundWithStartAngle(_ startAngle: Type, endAngle: Type...
    

    ... it would be translated to an easier-to-read:

    [_barView addBarBackgroundWithStartAngle: endAngle: ...]
    

    I hope this helps.