60

高可用型Codable

 5 years ago
source link: http://www.cocoachina.com/ios/20190318/26575.html?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

先放 Github地址

优点

  • Bool Int Double String等常用类型相互转换

  • jsonObject转String

  • 可带默认值

  • Swift版NSNumber,支持optional修饰的数字转到OC使用

互转原理

通过重载KeyedDecodingContainer的解析方法decodeIfPresent,在其中做了各种类型的兼容,所以只有在对象定义为optional的时候才会有以上兼容操作。

同时要注意的是重载只在internal范围生效,所以如果对象的定义在另外一个module是不会有效果的.

YZJAnyDecodable支持

YZJAnyDecodable对象主要是为了解决一个key值解析对应会有多种结果的情况,例如key为data的值有时候返回数组,有时候返回字典,这个时候用YZJAnyDecodable来声明就能使用decode方法解析出来,而原生的Any并不支持Codable。

这里YZJAnyDecodable主要用来适配定义为String?的成员变量的解析,把它全转为String类型,用到的时候再进行解析

默认值

如果需要使用Codable解析后对没有的变量设置默认值, 声明一个 CodingKeys 枚举属性

并实现DefaultCodingKey 协议的 func defaultValue() -> Any?方法,在方法内设置需要返回的默认值

 class TestObject: Codable {
    var dString: String?

    enum CodingKeys: String, DefaultCodingKey {
        case dString

        func defaultValue() -> Any? {
            switch self {
            case .dString:
            return "1"
        }
    }
 }

基础类型转OC的支持

YZJNumber 主要是为了解决混编工程中Swift定义为Optional的对象转不了OC的问题,并支持了Codable

class TestObject: Codable {
    var numberBool: YZJNumber?
    var numberInt: YZJNumber?
    var numberDouble: YZJNumber?
    var numberNULL: YZJNumber?
    var numberNone: YZJNumber?
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK