Giter VIP home page Giter VIP logo

codableextension's Introduction

高可用型Codable

优点

  • Bool Int Double String等常用类型相互转换
  • jsonObject转String
  • 可带默认值
  • Swift版NSNumber,支持optional修饰的数字转到OC使用

互转原理

通过重载KeyedDecodingContainer的解析方法decodeIfPresent,在其中做了各种类型的兼容,所以只有在对象定义为optional的时候才会有以上兼容操作。 同时要注意的是重载只在internal范围生效,所以如果对象的定义在另外一个module是不会有效果的.

YZJAnyDecodable支持

YZJAnyDecodable对象主要是为了解决一个key值解析对应会有多种结果的情况,例如keydata的值有时候返回数组,有时候返回字典,这个时候用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?
}

codableextension's People

Stargazers

ː̗̀(ꙨꙨ)ː̖́迷の软糯 avatar  avatar tang--test avatar LQ avatar  avatar QiuDaniel avatar he15his avatar

Watchers

he15his avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.