This is an implementation of Swift's Encoder/Decoder protocols which uses NSDictionary
as its underlying container mechanism.
It allows you to take a native swift class or struct that confirms to the Codable protocol and convert it to, or initialise it from, a dictionary.
A lot of the code is actually taken from the Swift Foundation library's own JSONEncoder
and JSONDecoder
classes.
It turns out that those class actually work by using NSDictionary
as an intermediate step between JSON and the native type to be encoded/decoded. Unfortunately the underlying NSDictionary
support isn't exposed by Foundation, which is why I've done so here.
See this blog post for a bit more detail!
At the moment this module is best built using the Swift Package Manager with swift build
.
The unit tests can be run with swift test
.
Type-erased wrappers for Encodable
, Decodable
, and Codable
values.
This functionality is discussed in Chapter 3 of Flight School Guide to Swift Codable.
Add the AnyCodable package to your target dependencies in Package.swift
:
import PackageDescription
let package = Package(
name: "YourProject",
dependencies: [
.package(
url: "https://github.com/Flight-School/AnyCodable",
from: "0.2.3"
),
]
)
Then run the swift build
command to build your project.
import AnyCodable
let dictionary: [String: AnyEncodable] = [
"boolean": true,
"integer": 1,
"double": 3.14159265358979323846,
"string": "string",
"array": [1, 2, 3],
"nested": [
"a": "alpha",
"b": "bravo",
"c": "charlie"
]
]
let encoder = JSONEncoder()
let json = try! encoder.encode(dictionary)
let json = """
{
"boolean": true,
"integer": 1,
"double": 3.14159265358979323846,
"string": "string",
"array": [1, 2, 3],
"nested": {
"a": "alpha",
"b": "bravo",
"c": "charlie"
}
}
""".data(using: .utf8)!
let decoder = JSONDecoder()
let dictionary = try! decoder.decode([String: AnyDecodable].self, from: json)
AnyCodable
can be used to wrap values for encoding and decoding.
MIT
Mattt (@mattt)