Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/yockow/swiftcodabledictionary
Yet another workaround for SR-7788.
https://github.com/yockow/swiftcodabledictionary
Last synced: 24 days ago
JSON representation
Yet another workaround for SR-7788.
- Host: GitHub
- URL: https://github.com/yockow/swiftcodabledictionary
- Owner: YOCKOW
- License: mit
- Created: 2020-06-24T14:16:13.000Z (over 4 years ago)
- Default Branch: main
- Last Pushed: 2021-05-11T08:12:15.000Z (over 3 years ago)
- Last Synced: 2023-03-02T05:27:00.645Z (over 1 year ago)
- Language: Swift
- Homepage:
- Size: 14.6 KB
- Stars: 5
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.txt
Awesome Lists containing this project
README
# What is `SwiftCodableDictionary`?
Yet another workaround for [SR-7788](https://bugs.swift.org/browse/SR-7788).
## Overview
As [implemented in the standard library](https://github.com/apple/swift/blob/90cb347cd9552024ce2483e516b6f3788eca44be/stdlib/public/core/Codable.swift#L5521-L5635),
`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`](./Sources/CodableDictionary/CodableDictionaryKey.swift)
that inherits from `Hashable` and `CodingKey`.
The point is that `Key` does not have to conform to `Codable`.## Usage
```Swift
import Foundation
import CodableDictionaryenum Key: String, CodableDictionaryKey {
case key
// No additional implementation is required,
// because `CodableDictionaryKey` provides default implementation.
}let dictionary: CodableDictionary = [.key: "value"]
let json = String(data: try JSONEncoder().encode(dictionary), encoding: .utf8)!
print(json) // -> {"key":"value"}let decoded = try JSONDecoder().decode(CodableDictionary.self, from: json.data(using: .utf8)!)
print(dictionary == decoded) // -> true```
# Requirements
- Swift 6, 5
- OS
* macOS
* Linux# License
MIT License.
See "LICENSE.txt" for more information.