Search code examples
objective-cswiftforward-declaration

How can I use method of an ObjC class which contains a forward declare Swift class in Swift?


//CoolSwiftClass.swift
@objc(MyCoolSwiftClass)
class CoolSwiftClass: NSObject {}

//MyObjCViewController.h
@class MyCoolSwiftClass;
@interface MyObjCViewController : UIViewController
- (instancetype)initWithMyCoolSwiftClass:(MyCoolSwiftClass *)myCoolSwiftClassInstance;
@end

//SadSwiftClass.swift
class SadSwiftClass: UIViewController {
  override func loadView() {
    super.loadView()
    //This won't work
    let myObjCViewController = MyObjCViewController(coolSwiftClass: coolSwiftClassInstance)
  }
}

It seems that Swift can find the forward declaration MyCoolSwiftClass but it cannot find out that it's actually the CoolSwiftClass.

screenshot

And I didn't find anything that can help me in Swift and Objective-C in the Same Project.

Update at 2015-11-19 13:34 CST

Just upload a repo to GitHub: SO33775908

Update at 2015-11-19 13:47 CST

Just find out a workaround:

No special ObjC name. Checkout branch No special ObjC name

Update at 2015-11-19 14:47 CST

Another workaround which generate warnings:

@compatibility_alias with several warnings


Solution

  • The best way I ever found is the workaround 1:

    No special ObjC name

    And if you have used that special ObjC name for a while, you can use something like this:

    //ClassName_Alias.h
    #define MyCoolSwiftClass CoolSwiftClass
    
    //CoolSwiftClass.swift
    @objc
    class CoolSwiftClass: NSObject {}
    

    Please checkout Question Update 1 for the sample repo.