Swiftpack.co -  YOCKOW/SwiftCodableDictionary as Swift Package
Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
YOCKOW/SwiftCodableDictionary
Yet another workaround for SR-7788.
.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: 5 weeks ago

Ad: Job Offers

iOS Software Engineer @ Perry Street Software
Perry Street Software is Jack’d and SCRUFF. We are two of the world’s largest gay, bi, trans and queer social dating apps on iOS and Android. Our brands reach more than 20 million members worldwide so members can connect, meet and express themselves on a platform that prioritizes privacy and security. We invest heavily into SwiftUI and using Swift Packages to modularize the codebase.

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