26
votes

Im in a situation where I need to use Objective-C category to extend a Swift class. I've done something as follows:

In "SomeClass.swift":

class SomeClass: NSObject {
}

In "SomeClass+Extension.h":

#import "Project-Swift.h"
@interface SomeClass (Extension) 
-(void)someMethod();
@end

This has worked well. And if I try to use the SomeClass extension in my Objective C code, it is fine.

The problem is, if I want to use someMethod() in a another Swift class, I will need to put the SomeClass+Extension.h file into my ObjC-BridgingHeader.h file.

But doing this will cause a circular dependency, because SomeClass+Extension.h also imports Project-Swift.h.

Does anyone have a good way to get around this?

Please note that simply forward declaring the class in the category header will not work, as categories cannot use forward declarations for it's own implementation as so:

@class SomeClass without importing Project-Swift.h will give a compile error.

3
@TroyT the solution you posted will not work, because this is a objective-C category, in a category you cannot simply forward declare a class, you must import the header file of the class your extending.stephen
First of all try to understand the difference between @class and #import you can find an excellent answer here stackoverflow.com/questions/322597/class-vs-importJohnykutty
@Johnykutty I know the difference between @class and #import. But in this case @class will not work because it's a category. In a category you must explicitly import the header file of the class your extending, if you try to do forward declaration you will get a class undefined error. So unforunately your solution will not work.stephen
even if its a class @ class will not work, because @ class directive says the compiler only that it is a class, no other informations like its properties, methods, superclass etc. If you want to use them you should import the corresponding header fileJohnykutty

3 Answers

19
votes

The Bad

i too have been fighting this issue a bunch. unfortunately the documentation pretty explicitly states that this pattern is not allowed:

To avoid cyclical references, don’t import Swift code into an Objective-C header (.h) file. Instead, you can forward declare a Swift class or protocol to reference it in an Objective-C interface.

Forward declarations of Swift classes and protocols can only be used as types for method and property declarations.

also throughout the the linked page you will notice it keeps mentioning to import the generated header specifically into the .m file:

To import Swift code into Objective-C from the same target

Import the Swift code from that target into any Objective-C .m file within that target

The Good

one solution that may work for you is to create a swift extension that redefines each method you need in the category. it is fragile and ugly, but arguably the cleanest solution.

/**
 Add category methods from objc here (since circular references prohibit the ObjC extension file)
 */
extension SomeClass {
    @nonobjc func someMethod() {
        self.performSelector(Selector("someMethod"))
    }
}
  • adding the @noobjc to the front allows the same method signature to be used w/o overriding the ObjC implementation
  • now the import "SomeClass+Extension.h" from the bridging header can be removed

if support for more than two input params is needed, or tighter type coupling is desired i would recommend using the runtime to call the underlying function. a great description is here.

3
votes

From the Interoperability guide, we cannot directly access the subclassed / categorized / extensioned Objc-objects for the .swift [SomeClass] class.

But as a turn-around, we can do this:

For Variables , we can do this:

extension Class {
    private struct AssociatedKeys {
        static var DescriptiveName = "sh_DescriptiveName"
    }

    var descriptiveName: String? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.DescriptiveName) as? String
        }

        set {
            if let newValue = newValue {
                objc_setAssociatedObject(
                    self,
                    &AssociatedKeys.DescriptiveName,
                    newValue as NSString?,
                    .OBJC_ASSOCIATION_RETAIN_NONATOMIC
                )
            }
        }
    }
}

For Methods, we can use method_swizzling which is not recommended.

2
votes

As one simple solution, you can move the extension to your Swift code. Then you won't have any dependency problems.