Swift 无法在 ObjC 中访问 ViewModel 属性

Swift ViewModel properties can't access in ObjC

在 Swift 项目中包含,

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); 

// 访问任何 属性 都会出现此错误

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

如果您希望能够在 Objective-C class 的实现文件中访问 class 的属性,您需要导入 header class。简单地通过执行 @class YourClass 转发声明 class 只会使类型本身可见,但不会公开其 properties/methods.

由于 Swift 文件没有 header,您需要导入模块的 Swift header。

所以在你的 ListViewController.m 中做

#import <YourModule/YourModule-Swift.h>

在您的 Objective-C 实施中,您需要导入 Xcode 为 Swift 生成的头文件。将此添加到您的导入中,用您的目标名称替换 ProductModuleName

#import "ProductModuleName-Swift.h"