Swiftpack.co - YOCKOW/SwiftCodableDictionary as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by YOCKOW.
YOCKOW/SwiftCodableDictionary 1.0.1
Yet another workaround for SR-7788.
⭐️ 5
🕓 2 years ago
.package(url: "https://github.com/YOCKOW/SwiftCodableDictionary.git", from: "1.0.1")

What is SwiftCodableDictionary?

Yet another workaround for SR-7788.

Overview

As implemented in the standard library, Dictionary can be en/decoded in/from a keyed container only if the dictionary uses String or Int keys. An unkeyed container is used to encode Dictionary even if Key conforms to Codable, and a keyed container cannot be decoded even if Key can be decoded from a string representation.

CodableDictionary resolves the issue. CodableDictionary can be en/decoded while its Key conforms to CodableDictionaryKey that inherits from Hashable and CodingKey. The point is that Key does not have to conform to Codable.

Usage

import Foundation
import CodableDictionary

enum Key: String, CodableDictionaryKey { 
   case key
   // No additional implementation is required,
   // because `CodableDictionaryKey` provides default implementation.
}

let dictionary: CodableDictionary<Key, String> = [.key: "value"]

let json = String(data: try JSONEncoder().encode(dictionary), encoding: .utf8)!
print(json) // -> {"key":"value"}

let decoded = try JSONDecoder().decode(CodableDictionary<Key, String>.self, from: json.data(using: .utf8)!)
print(dictionary == decoded) // -> true

Requirements

  • Swift 5
  • OS
    • macOS
    • Linux

License

MIT License.
See "LICENSE.txt" for more information.

GitHub

link
Stars: 5
Last commit: 2 years ago
Advertisement: IndiePitcher.com - Cold Email Software for Startups

Release Notes

1.0.1
1 year ago

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics