Search code examples
objective-cswiftswift-extensions

Accessing Obj-C properties in Swift extension file


I started writing Swift extensions on my view controllers. So I have three files right now:

My header file, ViewController.h:

@interface MyViewController : UIViewController

@end

My Obj-C implementation file, ViewController.m:

@interface MyViewController () <UIScrollViewDelegate>
@property (strong, nonatomic) UIScrollView *scrollView;
@end

@implementation MyViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    self.scrollView = [[UIScrollView alloc] init];
    [self customiseScrollView]; //This is Swift method called from Obj-C file
}

@end

And finally, ViewController.swift:

extension MyViewController {

    func customiseScrollView() {

    }
}

My question is, is it possible to access my Obj-C properties from my Swift implementation file? Every time I refer to it, I got an error:

Value of type 'MyViewController' has no member 'scrollView'

Bonus 1: Can someone also clarify if the Swift component can see what the .m is a delegate of as well. (To clarify, doing scrollView.delegate = self in Swift is a compile error because the Swift file does not realise that the .m file is a UIScrollViewDelegate).

Bonus 2: Can Swift extension file call Obj-C methods that are declared from the .m counterpart?


Solution

  • I think that you can't access private properties from extension. Your scrollView property is in .m file, not .h - which means it's private and it's not visible from extension file.

    Solution: move

    @property (strong, nonatomic) UIScrollView *scrollView;
    

    to your header file.