Search code examples
iosobjective-cswiftbridging-headerobjective-c-swift-bridge

Can't see Swift variable/method in Objective C


I am unable to see the method/variable to set myVar to true from Objective C even tough I've added the @objc and public modifiers and there is no Bool in the setMyVarTrue() method's signature.

This is probably caused by the difference between Swift's Bool and Objective C's BOOL.

Other class methods/variables are visible, just this particular one isn’t.

How is is possible to set Swift's Bool from Objective C?

Swift code:

public class MyViewController : UIViewController {
    public var myVar:Bool = false

    @objc public func setMyVarTrue() {
        self.myVar = true
    }
}

Objective C code:

MyViewController* myViewController = [MyViewController new];
myViewController.myVar = true // Variable not found
myViewController.setMyVarTrue() // Method not found
[self presentViewController:myViewController animated:NO completion:nil];

Solution

  • The solution was to clean and rebuild the project. Xcode generates the swift bridging header automatically and in my case it was stopping the build process with a (variable/method not found) error prior to regenerating the bridging header.

    SWIFT_CLASS("_TtC11MyProject25MyViewController")
    @interface MyViewController : UIViewController
    @property (nonatomic, strong) MBProgressHUD * _Nonnull progressIndicator;
    - (nonnull instancetype)initWithNibName:(NSString * _Nullable)nibNameOrNil bundle:(NSBundle * _Nullable)nibBundleOrNil OBJC_DESIGNATED_INITIALIZER;
    - (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER;
    - (void)viewDidLoad;
    - (void)viewWillAppear:(BOOL)animated;
    - (void)submitProgressHandler:(NSNotification * _Nonnull)notification;
    - (void)submitSuccessHandler;
    - (void)submitFailureHandler:(NSNotification * _Nonnull)notification;
    - (void)subscribe;
    - (void)unsubscribe;
    @end
    

    Now it works fine:

    SWIFT_CLASS("_TtC11MyProject25MyViewController")
    @interface MyViewController : UIViewController
    @property (nonatomic, strong) MBProgressHUD * _Nonnull progressIndicator;
    @property (nonatomic) BOOL closing;
    - (nonnull instancetype)initWithNibName:(NSString * _Nullable)nibNameOrNil bundle:(NSBundle * _Nullable)nibBundleOrNil OBJC_DESIGNATED_INITIALIZER;
    - (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER;
    - (void)viewDidLoad;
    - (void)viewWillAppear:(BOOL)animated;
    - (void)setClosingTrue;
    - (void)submitProgressHandler:(NSNotification * _Nonnull)notification;
    - (void)submitSuccessHandler;
    - (void)submitFailureHandler:(NSNotification * _Nonnull)notification;
    - (void)subscribe;
    - (void)unsubscribe;
    @end