this repo has no description
at main 62 lines 2.5 kB view raw
1// 2// KeyDecodingStrategy.swift 3// URLQueryItemCoder 4// 5// Created by Kyle Hughes on 4/10/23. 6// 7 8/// The strategy to use for automatically changing the value of keys before decoding. 9public enum KeyDecodingStrategy: Sendable { 10 /// Convert from "snake_case_keys" to "camelCaseKeys" before attempting to match a key with the one specified by 11 /// each type. 12 /// 13 /// The conversion to upper case uses `Locale.system`, also known as the ICU "root" locale. This means the result 14 /// is consistent regardless of the current user's locale and language preferences. 15 /// 16 /// Converting from snake case to camel case: 17 /// 18 /// 1. Capitalizes the word starting after each `_` 19 /// 2. Removes all `_` 20 /// 3. Preserves starting and ending `_` (as these are often used to indicate private variables or other metadata). 21 /// 22 /// For example, `one_two_three` becomes `oneTwoThree`. `_one_two_three_` becomes `_oneTwoThree_`. 23 /// 24 /// - Note: Using a key decoding strategy has a nominal performance cost, as each string key has to be inspected 25 /// for the `_` character. 26 case convertFromSnakeCase 27 28 /// Provide a custom conversion from the key in the encoded JSON to the keys specified by the decoded types. 29 /// 30 /// The full path to the current decoding position is provided for context (in case you need to locate this key 31 /// within the payload). The returned key is used in place of the last component in the coding path before decoding. 32 /// 33 /// If the result of the conversion is a duplicate key, then only one value will be present in the container for 34 /// the type to decode from. 35 case custom(@Sendable (_ codingPath: [CodingKey]) -> CodingKey) 36 37 /// Use the keys specified by each type. 38 /// 39 /// This is the default strategy. 40 case useDefaultKeys 41 42 // MARK: Public Static Interface 43 44 /// The default decoding strategy. 45 /// 46 /// Equals `.useDefaultKeys`. 47 public static let `default`: Self = .useDefaultKeys 48 49 // MARK: Internal Instance Interface 50 51 internal func encode(_ key: any CodingKey, at codingPath: [any CodingKey]) -> any CodingKey { 52 switch self { 53 case .convertFromSnakeCase: 54 return StringCodingKey(stringValue: key.stringValue.convertToSnakeCase()) 55 case let .custom(encoder): 56 return encoder(codingPath + [key]) 57 case .useDefaultKeys: 58 return key 59 } 60 } 61} 62