wildthink / DictionaryCoding

Swift Decoder/Encoder which converts to/from dictionaries.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Test results Latest release swift 5.0 shield swift dev shield Platforms: macOS, iOS, tvOS, watchOS

Test results Latest release Swift 5.0 Platforms: iOS, macOS, tvOS, watchOS, Linux

DictionaryCoding

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!

Build Instructions

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.

AnyCodable

Build Status License Swift Version

Type-erased wrappers for Encodable, Decodable, and Codable values.

This functionality is discussed in Chapter 3 of Flight School Guide to Swift Codable.

Installation

Swift Package Manager

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.

Usage

AnyEncodable

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)

AnyDecodable

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

AnyCodable can be used to wrap values for encoding and decoding.

License

MIT

Contact

Mattt (@mattt)

About

Swift Decoder/Encoder which converts to/from dictionaries.

License:Other


Languages

Language:Swift 99.2%Language:Ruby 0.8%Language:Shell 0.1%