Swift 4.1 中的 Codable 改进

892 阅读2分钟

2018-2-24.jpeg

Apple 在 Swift 4.0 中作了很多的改进,其中我个人最喜欢的就是 Codable 协议的出现。它让 Swift 自带了 JSON 、 XML 结构化数据和 Model 的映射和转换能力。

Codable 最常见的使用场景就是:APP 发起网络请求,然后我们将服务端响应的 JSON 数据转换为对应的 Model 实体。由于服务端的编程规范可能与客户端存在差异, Codable 默认数据转换实现可能不再适用。例如,服务端可能使用的蛇形命名方式而客户端使用的是驼峰。此时我们就需要在客户端自己动手实现映射关系。

struct Mac: Codable {
    var name: String
    var screenSize: Int
    var cpuCount: Int
}

let jsonString = """
[
    {
	"name": "MacBook Pro",
        "screen_size": 15,
        "cpu_count": 4
    },
    {
        "name": "iMac Pro",
        "screen_size": 27,
        "cpu_count": 18
    }
]
"""

let jsonData = Data(jsonString.utf8)

let decoder = JSONDecoder()

do {
    let macs = try decoder.decode([Mac].self, from: jsonData)
    print(macs)
} catch {
    print(error.localizedDescription)
}

上诉代码并不能完成理想的解码操作,因为 Codable 的默认实现无法将蛇形变量名映射到对应的驼峰属性上。所以在 Swift 4.0 中我们需要对 Mac 进行部分改造:

struct Mac: Codable {
    var name: String
    var screenSize: Int
    var cpuCount: Int

    enum CodingKeys : String, CodingKey {
          case name
          case screenSize = "screen_size"
          case cpuCount = "cpu_count"
    }
}

好在 Swift 4.1 对此作出了改进。现在我们可以通过设置 *JSONDecoder * 的 keyDecodingStrategy 就能实现不同编程规范之间解码操作了。与之对应,JSONEncoder 也有一个 keyEncodingStrategy 属性用于不同编程规范之间的编码操作。所以上诉代码可以简化为:

struct Mac: Codable {
    var name: String
    var screenSize: Int
    var cpuCount: Int
}

let jsonString = """
[
    {
	"name": "MacBook Pro",
        "screen_size": 15,
        "cpu_count": 4
    },
    {
        "name": "iMac Pro",
        "screen_size": 27,
        "cpu_count": 18
    }
]
"""

let jsonData = Data(jsonString.utf8)

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase

do {
    let macs = try decoder.decode([Mac].self, from: jsonData)
    print(macs)
} catch {
    print(error.localizedDescription)
}

如果你想进行反向转换操作的话,代码也非常简单:

let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
let encoded = try encoder.encode(macs)

当然,我们还可以对转换策略进行自定义实现以其实现一些特定需求。具体的使用方式可以参照代码