Search code examples
objective-cswiftextension-methodscgimage

Using a Swift extension method in Objective-C


I have an objective-c project which includes a swift file. I've created the bridging header and imported the ProjectSwift.h into the main file etc.

I am trying to use methods from the extensions stored in the Swift file, but am confused by the syntax. When it was class methods I used @objc in front of my Swift methods, but currently with the extensions I have no @objc or @nonobjc (when I put @objc in front of the extension declaration I got:

Method cannot be in an @objc extension of a class (without @nonobjc) because Core Foundation types are not classes in Objective-C

And if I tried @objc in front of individual methods I got:

Method cannot be marked @objc because Core Foundation types are not classes in Objective-C

My Swift code:

extension CGImage {
    public func someFunction(var1: Int, var2: Int){
        return someThing(someVariables)
    }
}

My Objective-C:

#import "MyProject-Swift.h"

CGImage *temp = someFunction(var1, var2);//Must use 'struct' tag to refer to type 'CGImage'

#import "MyProject-Swift.h"

struct CGImage *temp = someFunction(var1, var2); //Implicit declaration of function 'someFunction' is invalid in C99

And the method is not showing up with autocomplete so I'm guessing I'm screwing up the syntax in my ObjC code or I need some different extension version of @objc in my Swift code.


Solution

  • The error tells all. CGImage isn't a class in Objective-C. You can't use a Swift extension to CGImage in Objective-C. You can only use a Swift extension in Objective-C if the Swift extension is on something that is a class in Objective-C.

    In short, there is no way you can use your someFunction in your CGImage extension in your Objective-C code.