<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/xhtml; charset=utf-8">
</head>
<body>
<div style="font-family:sans-serif"><div style="white-space:normal">
<p dir="auto">Hi Norio,</p>
<p dir="auto">There are two reasons that I think this is valuable over doing something in <code style="background-color:#F7F7F7; border-radius:3px; margin:0; padding:0 0.4em" bgcolor="#F7F7F7">CodingKeys</code>:</p>
<ol>
<li value="1">The definition you give your coding keys affects all encoding formats. JSON is a format where snake_case can be relatively common, so the transformation makes a lot of sense there. For other formats, like plist files or otherwise, the transformation might not make as much sense. Instead of affecting all of your coding keys globally, this limits it to JSON.</li>
<li value="2">More importantly, this allows you to transform keys of things which you don’t necessarily own. If you’re working with types that you didn’t write (but which are expected to have snake_case keys nonetheless), this allows you to perform that transformation. If this were instead an annotation on <code style="background-color:#F7F7F7; border-radius:3px; margin:0; padding:0 0.4em" bgcolor="#F7F7F7">CodingKeys</code> directly, you wouldn’t be able to perform it on types you don’t directly own.</li>
</ol>
<p dir="auto">— Itai</p>
<p dir="auto">On 6 Nov 2017, at 17:39, Norio Nomura via swift-evolution wrote:</p>
</div>
<div style="white-space:normal"></div>
<blockquote style="border-left:2px solid #777; color:#777; margin:0 0 5px; padding-left:5px"><div id="42AB9958-B5CA-40A3-8C1F-C594DC5BCA0D"><div dir="ltr">Hi Tony,<div><br></div><div>Is it better for us to choose on `Codable` side whether `rawValue` of `CodingKeys` should be generated with snake_case?<br></div><div>It seems to be more consistent with the current method of setting `rawValue` of `CodingKeys` on `Codable` side.<br></div><div><br></div><div>Thanks,</div><div>--</div><div>@norio_nomura</div></div><div class="gmail_extra"><br><div class="gmail_quote">2017-11-07 5:54 GMT+09:00 Tony Parker via swift-evolution <span dir="ltr"><<a href="mailto:swift-evolution@swift.org" target="_blank">swift-evolution@swift.org</a>></span>:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div style="word-wrap:break-word;line-break:after-white-space">Hi everyone,<div><br></div><div>While we have no formal process at this time for proposals of changes to Foundation-only code, I would still like to post one that we have run through our internal process here for additional public comment.</div><div><br></div><div>Link to PR with proposal content:</div><div><br></div><div><a href="https://github.com/apple/swift-corelibs-foundation/pull/1301" target="_blank">https://github.com/apple/<wbr>swift-corelibs-foundation/<wbr>pull/1301</a></div><div><br></div><div>Link to implementation for the overlay:</div><div><br></div><div><a href="https://github.com/apple/swift/pull/12779" target="_blank">https://github.com/apple/<wbr>swift/pull/12779</a></div><div><br></div><div>Markdown follows.</div><div><br></div><div>Thanks,</div><div>- Tony</div><div><br></div><div><div># Key Strategies for JSONEncoder and JSONDecoder</div><div><br></div><div>* Proposal: SCLF-0001</div><div>* Author(s): Tony Parker <<a href="mailto:anthony.parker@apple.com" target="_blank">anthony.parker@apple.com</a>></div><div><br></div><div>##### Related radars or Swift bugs</div><div><br></div><div>* <<a>rdar://problem/33019707</a>> Snake case / Camel case conversions for JSONEncoder/Decoder</div><div><br></div><div>##### Revision history</div><div><br></div><div>* **v1** Initial version</div><div><br></div><div>## Introduction</div><div><br></div><div>While early feedback for `JSONEncoder` and `JSONDecoder` has been very positive, many developers have told us that they would appreciate a convenience for converting between `snake_case_keys` and `camelCaseKeys` without having to manually specify the key values for all types.</div><div><br></div><div>## Proposed solution</div><div><br></div><div>`JSONEncoder` and `JSONDecoder` will gain new strategy properties to allow for conversion of keys during encoding and decoding.</div><div><br></div><div>```swift</div><div>class JSONDecoder {</div><div> /// The strategy to use for automatically changing the value of keys before decoding.</div><div> public enum KeyDecodingStrategy {</div><div> /// Use the keys specified by each type. This is the default strategy.</div><div> case useDefaultKeys</div><div> </div><div> /// Convert from "snake_case_keys" to "camelCaseKeys" before attempting to match a key with the one specified by each type.</div><div> /// </div><div> /// The conversion to upper case uses `Locale.system`, also known as the ICU "root" locale. This means the result is consistent regardless of the current user's locale and language preferences.</div><div> ///</div><div> /// Converting from snake case to camel case:</div><div> /// 1. Capitalizes the word starting after each `_`</div><div> /// 2. Removes all `_`</div><div> /// 3. Preserves starting and ending `_` (as these are often used to indicate private variables or other metadata).</div><div> /// For example, `one_two_three` becomes `oneTwoThree`. `_one_two_three_` becomes `_oneTwoThree_`.</div><div> ///</div><div> /// - Note: Using a key decoding strategy has a nominal performance cost, as each string key has to be inspected for the `_` character.</div><div> case convertFromSnakeCase</div><div> </div><div> /// Provide a custom conversion from the key in the encoded JSON to the keys specified by the decoded types.</div><div> /// The full path to the current decoding position is provided for context (in case you need to locate this key within the payload). The returned key is used in place of the last component in the coding path before decoding.</div><div> case custom(([CodingKey]) -> CodingKey)</div><div> }</div><div> </div><div> /// The strategy to use for decoding keys. Defaults to `.useDefaultKeys`.</div><div> open var keyDecodingStrategy: KeyDecodingStrategy = .useDefaultKeys</div><div>}</div><div><br></div><div>class JSONEncoder {</div><div> /// The strategy to use for automatically changing the value of keys before encoding.</div><div> public enum KeyEncodingStrategy {</div><div> /// Use the keys specified by each type. This is the default strategy.</div><div> case useDefaultKeys</div><div> </div><div> /// Convert from "camelCaseKeys" to "snake_case_keys" before writing a key to JSON payload.</div><div> ///</div><div> /// Capital characters are determined by testing membership in `CharacterSet.<wbr>uppercaseLetters` and `CharacterSet.<wbr>lowercaseLetters` (Unicode General Categories Lu and Lt).</div><div> /// The conversion to lower case uses `Locale.system`, also known as the ICU "root" locale. This means the result is consistent regardless of the current user's locale and language preferences.</div><div> ///</div><div> /// Converting from camel case to snake case:</div><div> /// 1. Splits words at the boundary of lower-case to upper-case</div><div> /// 2. Inserts `_` between words</div><div> /// 3. Lowercases the entire string</div><div> /// 4. Preserves starting and ending `_`.</div><div> ///</div><div> /// For example, `oneTwoThree` becomes `one_two_three`. `_oneTwoThree_` becomes `_one_two_three_`.</div><div> ///</div><div> /// - Note: Using a key encoding strategy has a nominal performance cost, as each string key has to be converted.</div><div> case convertToSnakeCase</div><div> </div><div> /// Provide a custom conversion to the key in the encoded JSON from the keys specified by the encoded types.</div><div> /// The full path to the current encoding position is provided for context (in case you need to locate this key within the payload). The returned key is used in place of the last component in the coding path before encoding.</div><div> case custom(([CodingKey]) -> CodingKey)</div><div> }</div><div> </div><div> </div><div> /// The strategy to use for encoding keys. Defaults to `.useDefaultKeys`.</div><div> open var keyEncodingStrategy: KeyEncodingStrategy = .useDefaultKeys</div><div>}</div><div>```</div><div><br></div><div>## Detailed design</div><div><br></div><div>The strategy enum allows developers to pick from common actions of converting to and from `snake_case` to the Swift-standard `camelCase`. The implementation is intentionally simple, because we want to make the rules predictable.</div><div><br></div><div>Converting from snake case to camel case:</div><div><br></div><div>1. Capitalizes the word starting after each `_`</div><div>2. Removes all `_`</div><div>3. Preserves starting and ending `_` (as these are often used to indicate private variables or other metadata).</div><div><br></div><div>For example, `one_two_three` becomes `oneTwoThree`. `_one_two_three_` becomes `_oneTwoThree_`.</div><div><br></div><div>Converting from camel case to snake case:</div><div><br></div><div>1. Splits words at the boundary of lower-case to upper-case</div><div>2. Inserts `_` between words</div><div>3. Lowercases the entire string</div><div>4. Preserves starting and ending `_`.</div><div><br></div><div>For example, `oneTwoThree` becomes `one_two_three`. `_oneTwoThree_` becomes `_one_two_three_`.</div><div><br></div><div>We also provide a `custom` action for both encoding and decoding to allow for maximum flexibility if the built-in options are not sufficient.</div><div><br></div><div>## Example</div><div><br></div><div>Given this JSON:</div><div><br></div><div>```</div><div>{ "hello_world" : 3, "goodbye_cruel_world" : 10, "key" : 42 }</div><div>```</div><div><br></div><div>Previously, you would customize your `Decodable` type with custom keys, like this:</div><div><br></div><div>```swift</div><div>struct Thing : Decodable {</div><div><br></div><div> let helloWorld : Int</div><div> let goodbyeCruelWorld: Int</div><div> let key: Int</div><div><br></div><div> private enum CodingKeys : CodingKey {</div><div> case helloWorld = "hello_world"</div><div> case goodbyeCruelWorld = "goodbye_cruel_world"</div><div> case key</div><div> }</div><div>}</div><div><br></div><div>var decoder = JSONDecoder()</div><div>let result = try! decoder.decode(Thing.self, from: data)</div><div>```</div><div><br></div><div>With this change, you can write much less boilerplate:</div><div><br></div><div>```swift</div><div>struct Thing : Decodable {</div><div><br></div><div> let helloWorld : Int</div><div> let goodbyeCruelWorld: Int</div><div> let key: Int</div><div>}</div><div><br></div><div>var decoder = JSONDecoder()</div><div>decoder.keyDecodingStrategy = .convertFromSnakeCase</div><div>let result = try! decoder.decode(Thing.self, from: data)</div><div>```</div><div><br></div><div>## Alternatives considered</div><div><br></div><div>None.</div></div><div><br></div></div><br>______________________________<wbr>_________________<br>
swift-evolution mailing list<br>
<a href="mailto:swift-evolution@swift.org">swift-evolution@swift.org</a><br>
<a href="https://lists.swift.org/mailman/listinfo/swift-evolution" rel="noreferrer" target="_blank">https://lists.swift.org/<wbr>mailman/listinfo/swift-<wbr>evolution</a><br>
<br></blockquote></div><br></div></div></blockquote>
<div style="white-space:normal">
<blockquote style="border-left:2px solid #777; color:#777; margin:0 0 5px; padding-left:5px">
</blockquote><blockquote style="border-left:2px solid #777; color:#777; margin:0 0 5px; padding-left:5px"><p dir="auto">_______________________________________________<br>
swift-evolution mailing list<br>
swift-evolution@swift.org<br>
<a href="https://lists.swift.org/mailman/listinfo/swift-evolution" style="color:#777">https://lists.swift.org/mailman/listinfo/swift-evolution</a></p>
</blockquote></div>
<div style="white-space:normal">
</div>
</div>
</body>
</html>