Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,27 @@ decoder.intDecodingStrategy = .clamping(roundingRule: .toNearestOrAwayFromZero)
let values = try decoder.decode([Int8].self, from: [10, 20.5, 1000, -Double.infinity])
```

## Key Strategy

Keys can be encoded to snake_case by setting the strategy:

```swift
var encoder = KeyValueEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase

// ["first_name": "fish", "surname": "chips"]
let dict = try encoder.encode(Person(firstName: "fish", surname: "chips))
```

And decoded from snake_case:

```swift
var decoder = KeyValueDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase

let person = try decoder.decode(Person.self, from: dict)
```

## UserDefaults
Encode and decode [`Codable`](https://developer.apple.com/documentation/swift/codable) types with [`UserDefaults`](https://developer.apple.com/documentation/foundation/userdefaults):

Expand Down
31 changes: 28 additions & 3 deletions Sources/KeyValueDecoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ public struct KeyValueDecoder: Sendable {
/// The strategy to use for decoding BinaryInteger types. Defaults to `.exact` for lossless conversion between types.
public var intDecodingStrategy: IntDecodingStrategy = .exact

/// The strategy to use for decoding each types keys.
public var keyDecodingStrategy: KeyDecodingStrategy = .useDefaultKeys

/// Initializes `self` with default strategy.
public init () {
self.userInfo = [:]
Expand Down Expand Up @@ -82,6 +85,15 @@ public struct KeyValueDecoder: Sendable {
/// Floating point conversions are also clamped, rounded when a rule is provided
case clamping(roundingRule: FloatingPointRoundingRule?)
}

/// Strategy to determine how to decode a type’s coding keys from String values.
public enum KeyDecodingStrategy: Sendable {
/// A key decoding strategy that converts snake-case keys to camel-case keys.
case convertFromSnakeCase

/// A key encoding strategy that doesn’t change key names during encoding.
case useDefaultKeys
}
}

#if canImport(Combine)
Expand All @@ -105,12 +117,14 @@ private extension KeyValueDecoder {
struct DecodingStrategy {
var optionals: NilDecodingStrategy
var integers: IntDecodingStrategy
var keys: KeyDecodingStrategy
}

var strategy: DecodingStrategy {
DecodingStrategy(
optionals: nilDecodingStrategy,
integers: intDecodingStrategy
integers: intDecodingStrategy,
keys: keyDecodingStrategy
)
}

Expand Down Expand Up @@ -381,7 +395,8 @@ private extension KeyValueDecoder {

func container(for key: Key) throws -> SingleContainer {
let path = codingPath.appending(key: key)
guard let value = storage[key.stringValue] else {
let kkk = strategy.keys.makeStorageKey(for: key.stringValue)
guard let value = storage[kkk] else {
let keyPath = codingPath.makeKeyPath(appending: key)
let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Dictionary does not contain key \(keyPath)")
throw DecodingError.keyNotFound(key, context)
Expand All @@ -395,7 +410,7 @@ private extension KeyValueDecoder {
}

func contains(_ key: Key) -> Bool {
return storage[key.stringValue] != nil
return storage[strategy.keys.makeStorageKey(for: key.stringValue)] != nil
}

func decodeNil(forKey key: Key) throws -> Bool {
Expand Down Expand Up @@ -640,6 +655,16 @@ private extension KeyValueDecoder {
}
}

extension KeyValueDecoder.KeyDecodingStrategy {

func makeStorageKey(for key: String) -> String {
switch self {
case .useDefaultKeys: return key
case .convertFromSnakeCase: return key.toSnakeCase()
}
}
}

extension BinaryInteger {

init?(from source: Double, using strategy: KeyValueDecoder.IntDecodingStrategy) {
Expand Down
Loading