2.5 · JSON coder options, property lists, UserDefaults

You already know how Codable synthesises a decoder. This section is about everything around it: the strategies you configure, the errors you read, the older untyped APIs, and the two small stores every app uses.

Mental model. The coder’s defaults are designed for Swift-to-Swift round trips, not for real servers. Most bugs are a default that does not match the other side.

Configuring JSON coders

Key names, dates, output format, and reading the error when it fails.

  1. What does keyDecodingStrategy do, and when does convertFromSnakeCase not match? 2.5.1 · L1
    By default a Swift property name must equal the JSON key. keyDecodingStrategy = .convertFromSnakeCase converts each incoming key (user_id) to lower camel case…
  2. How are dates encoded and decoded in JSON, and why are they 31 years off? 2.5.2 · L1
    JSON has no date type, so you choose a dateEncodingStrategy and dateDecodingStrategy. The default, .deferredToDate, writes a Double of seconds since the 2001…
  3. Which JSONEncoder and JSONDecoder options matter beyond keys and dates? 2.5.3 · L2
    On the encoder, outputFormatting controls the text. .sortedKeys makes the output deterministic. Without it dictionary keys come out in a changing order, which…
  4. How do you read a DecodingError, and how do you decode tolerantly? 2.5.4 · L2
    Decoding failures throw a DecodingError with four cases: keyNotFound, typeMismatch, valueNotFound and dataCorrupted. Each carries a Context whose codingPath…

JSON beyond Codable

The untyped route, and what it costs.

  1. When would you use JSONSerialization instead of Codable, and what does the untyped route cost? 2.5.5 · L3
    JSONSerialization parses JSON into an untyped tree of Any: NSDictionary, NSArray, NSString, NSNumber and NSNull. It suits shapes you cannot model in a type (a…

Property lists

The format behind Info.plist and UserDefaults.

  1. What is a property list, and where do you meet one? 2.5.6 · L1
    A property list is Apple’s simple serialisation format for small structured data: dictionaries and arrays of strings, numbers, booleans, dates and Data. You…

UserDefaults

Small settings, typed getters that lie, and what does not belong there.

  1. What is UserDefaults, what can it store, and why do its typed getters mislead? 2.5.7 · L1
    UserDefaults is a small persistent key-value store, saved as a property list in the app’s Preferences. It stores only property-list types: String, Number…
  2. What belongs in UserDefaults, and how do you design and test around it? 2.5.8 · L3
    Keep small, non-sensitive preferences and flags in UserDefaults. Secrets and tokens go in the Keychain; big or queryable data goes in files, Core Data or…

More in Foundation & stdlib