ContextCodable.swift
将 CodableWithConfiguration 迁移到旧操作系统版本和 Linux 的实现
为什么?
Apple 添加了 Codable
类型 - CodableWithConfiguration
,该类型允许在编码和解码时提供上下文。
但是,这些协议仅从 macOS 12 开始可用,并且仅在 macOS 15 中添加了对 JSONEncoder
和 JSONDecoder
的支持。Linux 完全不支持它们。
因此,我们创建了此库,它可在旧的 Swift 和平台上启用此 API。它有一定的速度损失,但是它确实可以工作!
入门教程
安装
包管理器
将以下依赖项添加到您的 Package.swift
.package(url: "https://github.com/tesseract-one/ContextCodable.swift.git", from: "0.1.0")
运行 swift build
来构建您的应用程序。
CocoaPods
将以下内容添加到您的 Podfile
pod 'ContextCodable.swift', '~> 0.1.0'
然后运行 pod install
示例
编码
import Foundation
import ContextCodable
struct SomeEncodable: ContextEncodable {
typealias EncodingContext = (top: String, internal: Date)
let internal: Internal
struct Internal: ContextEncodable {
typealias EncodingContext = Date
let value: Bool
func encode(to encoder: Encoder, context: EncodingContext) throws {
var container = encoder.unkeyedContainer()
try container.encode(value)
try container.encode(context)
}
}
enum CodingKeys: CodingKey {
case `internal`
case context
}
func encode(to encoder: Encoder, context: EncodingContext) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.internal, forKey: .internal, context: context.internal)
try container.encode(context.top, forKey: .context)
}
}
let value = SomeEncodable(internal: SomeEncodable.Internal(value: true))
let encoded = try JSONEncoder().encode(value, context: (top: "Test", internal: Date()))
print(String(data: encoded, encoding: .utf8)!)
解码
import Foundation
import ContextCodable
struct SomeDecodable: ContextDecodable {
typealias DecodingContext = (top: String, internal: Date)
let internal: Internal
let top: String
struct Internal: ContextDecodable {
typealias DecodingContext = Date
let value: Bool
let date: Date
init(from decoder: Decoder, context: DecodingContext) throws {
var container = try decoder.unkeyedContainer()
value = try container.decode(Bool.self)
date = context
}
}
enum CodingKeys: CodingKey {
case `internal`
case context
}
init(from decoder: Decoder, context: DecodingContext) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.internal = try decoder.decode(Internal.self, forKey: .internal, context: context.internal)
self.top = context.top
}
}
let json = Data("{\"internal\": [true]}".utf8)
let decoded = try JSONDecoder().decode(SomeDecodable.self, from: json, context: (top: "Test", internal: Date()))
print(decoded)
作者
许可
ContextCodable.swift 在 Apache 2.0 许可下可用。有关更多信息,请参阅 LICENSE 文件。