CodableHelper 0.1.2

CodableHelper 0.1.2

Maintained by zgj.



  • By
  • zgj

CodableHelper

方便快捷的Codable的extension,解放你的双手

使用方法eg:

struct Student {
    let name: String
    let sex: String
    let age: Int
    let school: String
    let pic: URL
    let scores: Double
    let ff: Double? // 这个字段可能为空(即后台不反回这个字段)
    let ss: Int? // 这个字段可能为空(即后台不反回这个字段)
 }
 

let c = try decoder.container(keyedBy: CodingKeys.self)

1: 解放decode(type, forKey: key)

a: 原始类型---即后台直接返回的类型跟所需类型一样

使用前:

name = try c.decode(String.self, forKey: .name)

使用后:

name = try c[.name, String.self]()

b: 非原始类型,即把String类型转换成需要的类型(可以方便快捷的把后台返回的String类型转换成Int/Double/Float/URL......只要遵守ConvertFromString协议即可)

使用前:

if let age = try? c.decode(String.self, forKey: .age) {
  self.age = Int(age) ?? defaultValue
} else {
  self.age = defaultValue
}

使用后:

age = try c[.age](Int.self)

2: 解放decodeIfPresent(type, forKey: key)

a: 原始类型---即后台直接返回的类型跟所需类型一样

使用前:

if let ff = c.decodeIfPresent(Double.self, forKey: .code) {
    self.ff = Double(ff) ?? defaultValue
}

使用后:

ff = try c[.ff, defaultValue](Double.self)

b: 非原始类型,即把String类型转换成需要的类型(可以方便快捷的把后台返回的String类型转换成Int/Double/Float/URL......只要遵守ConvertFromString协议即可)

使用前:

if let scores = c.decodeIfPresent(String.self, forKey: .code) {
    self.scores = Double(scores) ?? defaultValue
} else {
    scores = defaultValue
}

使用后:

scores = try c[.scores, defaultValue](Double.self) ?? defaultValue

CocoaPods

pod 'CodableHelper'