一个小问题 :Swift 与 OC 混编 HandyJson 解析 OC 类的办法

2,117 阅读1分钟

OC 项目向 Swift 转型中选择了 HandyJson 作为解析 Json 的工具库,发现使用了 HandyJson 后,一些 OC 类解析不了。

OCModel 是一个OC类。

/// OCModel.h

@interface OCModel : NSObject

@property (nonatomic,copy) NSString *userid;
@property (nonatomic,copy) NSString *memberid;

@end

UserModelSwift 业务类。

/// 这个是我们的业务类
class UserModel: HandyJSON {

    /// 成员列表, OCModel 是通过桥接的 OC类
    public var memberlist: [OCModel]?
}

结果发现 memberlist 会转换失败。

研究了一下HandyJson 框架,发现提供了这样的协议:

public protocol HandyJSONCustomTransformable: _ExtendCustomBasicType {}
public protocol HandyJSON: _ExtendCustomModelType {}
public protocol HandyJSONEnum: _RawEnumProtocol {}

/// _RawEnumProtocol
public protocol _RawEnumProtocol: _Transformable {

    static func _transform(from object: Any) -> Self?

    func _plainValue() -> Any?

}

extension RawRepresentable where Self: _RawEnumProtocol {

    public static func _transform(from object: Any) -> Self? {
        if let transformableType = RawValue.self as? _Transformable.Type {
            if let typedValue = transformableType.transform(from: object) {
                return Self(rawValue: typedValue as! RawValue)
            }
        }
        return nil
    }
    
    public func _plainValue() -> Any? {
        return self.rawValue
    }
}

所以你可以这样:

创建一个 swift 类,继承 OCModel

class Swift_OCModel: OCModel,HandyJSON,HandyJSONEnum {

    /// HandyJSONEnum 协议方法
    public func _plainValue() -> Any? {
        /// YYModel 的方法(可变更自己的)
        return self.modelToJSONObject()
    }
    
    static func _transform(from object: Any) -> Self? {
        /// YYModel 的方法(可变更自己的)
        let model = Swift_OCModel.model(withJSON: object)
        return model as? Self
    }

    required override init() {
        super.init()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

然后,memberlist: [OCModel]? -> memberlist: [Swift_OCModel]?,就可以正常解析了。

/// 这个是我们的业务类
class UserModel: HandyJSON {

    /// 成员列表, OCModel 是通过桥接的 OC类
    
    // public var memberlist: [OCModel]?
    public var memberlist: [Swift_OCModel]?
}