Case
JSONEncoder.KeyEncodingStrategy.convertToSnakeCase
iOS 8.0+
iPadOS 8.0+
Mac Catalyst 8.0+
macOS 10.10+
tvOS 9.0+
watchOS 2.0+
Convert from “camelCaseKeys” to “snake_case_keys” before writing a key to JSON payload.
case convertToSnakeCase
Discussion
Capital characters are determined by testing membership in Unicode General Categories Lu and Lt. 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.
Converting from camel case to snake case:
Splits words at the boundary of lower-case to upper-case
Inserts
_between wordsLowercases the entire string
Preserves starting and ending
_.
For example, oneTwoThree becomes one_two_three. _oneTwoThree_ becomes _one_two_three_.
Note
Using a key encoding strategy has a nominal performance cost, as each string key has to be converted.