DecodeFailable
[](https://travis-ci.org/George Marmaridis/DecodeFailable)
DecodeFailable 为您提供了一个定制的 Decodable
集合,解码个别元素可以静默失败。因此,JSON 数组中的格式错误或未知元素不会导致整个解码失败。
它还允许您轻松地为这些元素记录或添加自定义错误处理。
示例
要运行示例项目,请先克隆仓库,然后在 Example 目录下首先运行 pod install
。
要求
- iOS 8.0+
- Swift 4.2+
安装
CocoaPods
DecodeFailable 通过 CocoaPods 可用。要安装它,只需将以下行添加到您的 Podfile
pod 'DecodeFailable'
手动
如果您不希望使用 CocoaPods,可以将 DecodeFailable 手动集成到项目中。
用法
使用 DecodeFailable 非常简单。您只需要实现 init(from decoder: Decoder)
,并为您的数组解码使用 DecodeFailableArray
。
import DecodeFailable
struct GetPeopleResponse: Codable {
private enum CodingKeys: String, CodingKey {
case people
}
let people: [Person]
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.people = try container.decode(DecodeFailableArray<Person>.self, forKey: .people).elements
}
}
struct Person: Codable {
let id: String
let firstName: String
let lastName: String
}
作者
George Marmaridis
- https://github.com/gmarm
- https://twitter.com/gmarmas
- https://www.linkedin.com/in/gmarm
- [email protected]
许可
DecodeFailable 采用 MIT 许可。有关更多详细信息,请参阅 LICENSE 文件。