AnyCodable
对于 Encodable
、Decodable
和 Codable
值的泛型包装器。
这个功能在 Flight School Guide to Swift Codable 的第 3 章中有讨论。
安装
Swift Package Manager
将 AnyCodable 包添加到 Package.swift
中的目标依赖项。
import PackageDescription
let package = Package(
name: "YourProject",
dependencies: [
.package(
url: "https://github.com/Flight-School/AnyCodable",
from: "0.6.0"
),
]
)
然后运行 swift build
命令来构建您的项目。
CocoaPods
您可以通过将以下行添加到您的 Podfile
文件中来通过 CocoaPods 安装 AnyCodable
:
pod 'AnyCodable-FlightSchool', '~> 0.6.0'
运行 pod install
命令以下载库并将其集成到您的 Xcode 项目中。
注意 该库的模块名为 "AnyCodable",即使用它时,您需要将
import AnyCodable
添加到 Swift 代码的顶部,就像您使用其他安装方法一样。该依赖库名为 "AnyCodable-FlightSchool",因为已存在名为 "AnyCodable" 的依赖库。
Carthage
使用 Carthage 在您的 Xcode 项目中使用 AnyCodable
时,请在 Cartfile
中指定它。
github "Flight-School/AnyCodable" ~> 0.6.0
然后运行 carthage update
命令以构建框架,并将构建的 AnyCodable.framework 拖入您的 Xcode 项目中。
Usage
AnyEncodable
import AnyCodable
let dictionary: [String: AnyEncodable] = [
"boolean": true,
"integer": 1,
"double": 3.141592653589793,
"string": "string",
"array": [1, 2, 3],
"nested": [
"a": "alpha",
"b": "bravo",
"c": "charlie"
],
"null": nil
]
let encoder = JSONEncoder()
let json = try! encoder.encode(dictionary)
AnyDecodable
let json = """
{
"boolean": true,
"integer": 1,
"double": 3.141592653589793,
"string": "string",
"array": [1, 2, 3],
"nested": {
"a": "alpha",
"b": "bravo",
"c": "charlie"
},
"null": null
}
""".data(using: .utf8)!
let decoder = JSONDecoder()
let dictionary = try! decoder.decode([String: AnyDecodable].self, from: json)
AnyCodable
AnyCodable
可以用于包装值以进行编码和解码。
许可
MIT
联系
Mathew (@mattt)