Search code examples
iosobjective-cswiftmvvmviewmodel

Swift ViewModel properties can't access in ObjC


In Swift project contains,

CartViewModel.swift

@objc public class CartViewModel: NSObject {

    let apiService: APIService

    var alertMessage: String? {
        didSet {
            self.showAlertClosure?()
        }
    }
    var isShow: Bool = false {
        didSet {
            self.updateStatus?()
        }
    }
    @objc public var dataCount: Int {
        return models.count
    }
}

ListViewController.h

NS_ASSUME_NONNULL_BEGIN

@class CartViewModel;

@interface ListViewController : UIViewController
@property (nonatomic, strong) CartViewModel *viewModel;

@end

NS_ASSUME_NONNULL_END

ListViewController.m

NSLog(@"%@", self.viewModel.dataCount); 

// Accessing any property gives this error

Property 'dataCount' cannot be found in forward class object 'CartViewModel'


Solution

  • If you want to be able to access properties of a class inside the implementation file of an Objective-C class, you need to import the header of the class. Simply forward declaring the class by doing @class YourClass only makes the type itself visible, but it doesn't expose its properties/methods.

    Since Swift files don't have headers, you need to import the Swift header of your module.

    So in your ListViewController.m do

    #import <YourModule/YourModule-Swift.h>