根据HandyJSON官方仓库的使用介绍,在swift的枚举类型使用HandyJSON只需要让枚举遵守HandyJSONEnum协议即可。
To be convertable, An enum must conform to HandyJSONEnum protocol. Nothing special need to do now.
官方示例:
enum AnimalType: String, HandyJSONEnum {
case Cat = "cat"
case Dog = "dog"
case Bird = "bird"
}
struct Animal: HandyJSON {
var name: String?
var type: AnimalType?
}
let jsonString = "{\"type\":\"cat\",\"name\":\"Tom\"}"
if let animal = Animal.deserialize(from: jsonString) {
print(animal.type?.rawValue)
}
我的场景是,定义的枚举需要在OC中使用,所以用@objc public
修饰了我的枚举,定义如下:
@objc public enum ConnectInteractionType: UInt, HandyJSONEnum {
/// 未知
case unknown = 0
/// 触摸模式
case touch = 1
/// 指针模式(默认值)
case point = 2
func info() -> ConnectItemInfo {
switch self {
case .unknown:
return ConnectItemInfo(title: "")
case .touch:
return ConnectItemInfo(title: "Touch Mode", normalIconName: "icon_interaction_touch")
case .point:
return ConnectItemInfo(title: "Pointer Mode", normalIconName: "icon_interaction_point")
}
}
}
错误信息:
Thread 1: "-[__SwiftValue unsignedLongLongValue]: unrecognized selector sent to instance 0x28126eca0"
经过排查,只有当我的枚举遵守了该协议,才会产生这个错误,所以确定错误与HandyJSONEnum是有关的。
而且,如果该枚举不使用混编,也就是取消掉@objc public后,也不会出现这个问题,
所以总结一下是:当swift中的枚举需要在oc中混编时,使用HandyJSON解析时,会解析失败。