用于 Encodable
、Decodable
和 Codable
值的类型擦除包装器。
此功能在Flight School Guide to Swift Codable的第 3 章中讨论。
将 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
命令以构建您的项目。
您可以通过将以下行添加到您的 Podfile
中,使用 CocoaPods 安装 AnyCodable
pod 'AnyCodable-FlightSchool', '~> 0.6.0'
运行 pod install
命令来下载库并将其集成到您的 Xcode 项目中。
注意 此库的模块名称为 "AnyCodable" --- 也就是说,要使用它,您只需像使用任何其他安装方法一样,在 Swift 代码的顶部添加
import AnyCodable
。 该 pod 称为 "AnyCodable-FlightSchool",因为已有一个名为 "AnyCodable" 的 pod。
要使用 Carthage 在您的 Xcode 项目中使用 AnyCodable
,请在 Cartfile
中指定它
github "Flight-School/AnyCodable" ~> 0.6.0
然后运行 carthage update
命令来构建框架,并将构建好的 AnyCodable.framework 拖到您的 Xcode 项目中。
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)
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
可用于包装值以进行编码和解码。
MIT
Mattt (@mattt)