Codable 扩展,用于解码数组并捕获和记录所有解码错误
特性
SafeDecoder 为 Codable 模型提供了两项改进
- 在解码数组时,它可以跳过无效的对象,允许您的应用程序仅显示有效对象
- 它还可以收集所有解码错误并将它们发送到您的日志类或服务
如何安装
将其添加到您的 CocoaPods Podfile 中
pod 'SafeDecoder'
如何解码数组
为了安全地解码数组,在您模型的 init(from decoder:) 中只需调用 container.decodeArray() 并传入您的数组中的模型类型
import SafeDecoder
struct MyModel: Decodable {
var myArray: [CGRect]
enum CodingKeys: String, CodingKey {
case myArray
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
// to parse an array without re-thowing an error, call decodeArray()
myArray = try container.decodeArray(CGRect.self, forKey: .myArray)
}
}
如何安全解码
如果您想收集所有解码错误以便记录,请在这里实现自己的记录代码
SafeDecoder.logger = { error, typeName in
// replace with a call to your own logging library/service
print(error)
}
然后在模型的init(from decoder:)调用中,调用decoder.safeContainer(),然后调用container.decodeSafe()或container.decodeArraySafe()
SafeDecoder将收集所有错误并在抛出异常之前将它们记录
import SafeDecoder
struct MyModel: Decodable {
var myId: String
var myArray: [CGRect]
enum CodingKeys: String, CodingKey {
case myId
case myArray
}
public init(from decoder: Decoder) throws {
var container = try decoder.safeContainer(keyedBy: CodingKeys.self)
let _myId = try container.decodeSafe(String.self, forKey: .myId)
let _myArray = try container.decodeArraySafe(CGRect.self, forKey: .myArray)
guard
let myId = _myId,
let myArray = _myArray
else {
// this reference can be your object identifier to help find the issue with your data
throw container.getErrors(modelType: MyModel.self, reference: _myId)
}
self.myId = myId
self.myArray = myArray
}
}
抢购最后一点:)
一个优雅的解决方案,当键盘显示时保持视图可见https://github.com/IdleHandsApps/IHKeyboardAvoiding
居中且可重用的按钮样式,并连接到InterfaceBuilder https://github.com/IdleHandsApps/DesignableButton
一个扩展,可以轻松地将UINavigationBar设置为透明并隐藏阴影 https://github.com/IdleHandsApps/UINavigationBar-Transparent
作者
- Fraser Scott-Morrison ([email protected])
如果能听到任何使用SafeDecoder的酷应用,那将非常棒
许可证
在MIT许可证下分发