JSON Coding is what we need 90% of the time

Let's face the truth. If happen you work with any other data format than JSON, you're in a 10% niche (estimates may vary).

Even though the default JSONEncoder for Swift Codable is not the fastest - it's soooo convenient to use. Just make a struct or a class conforming to Codable protocol, and most of the job is done for you:

struct Dog: Codable {
  let name: String
}

encode:

let data = JSONEncoder().encode(encodableValue)

decode:

let dog = try JSONDecoder().decode(Dog.self, from: data)

Now, if encoder needs some adjustments, that are available, like output format, key encoding strategy etc. you need this:

let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
encoder.dateEncodingStrategy = .iso8601
encoder.dataEncodingStrategy = .base64
encoder.keyEncodingStrategy = .convertToSnakeCase
let data = encoder.encode(encodableValue)

Surely, now you'd like to keep the configured encoder around because most likely, you need the set up everywhere in the project, so you go with a class or struct (or global variable even) to store the encoder. It's getting cumbersome.

Remember how all we need is JSON? JSON is a text-based format, so for every encoding, you'll go with something like:

let jsonStr = String(data: data, encoding: .utf8)!

Can you do better?

Yes, you can.

If happen you need a faster decoder, try ZippyJSON, which is a drop-in replacement that works with Codable protocol out of the box.

If you crave for sexier syntax, you can go with JSONCodable and reduce the boilerplate to:

let data = try Dog(name: "bark").to(.json)
let data = try Dog(name: "bark").to(.jsonBase64)
let data = try Dog(name: "bark").to(.plist)

let dog = try Dog.from(data, format: .json)
let dog = try Dog.from(data, format: .jsonBase64)
let dog = try Dog.from(data, format: .plist)

or

let jsonStr = try Dog(name: "bark").toJSON()

Once a custom format is added to CustomFormat struct (aka. enum):

import JSONCodable
import ZippyJSON

extension CodableFormat {

  // Custom format
  static let jsonZippy = CodableFormat("jsonZippy", JSONEncoder(), ZippyJSONDecoder())
  
}

it's available as a format:

let dog = try Dog.from(data, format: .jsonZippy)

You get the idea.

I wish something like this API available in Standard Library. Sure, it's sugar syntax. I love it. But that just me.