Skip to content

Instantly share code, notes, and snippets.

@bricker
Last active April 5, 2021 06:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bricker/9d08133549a9422619d7b17b2c5a3915 to your computer and use it in GitHub Desktop.
Save bricker/9d08133549a9422619d7b17b2c5a3915 to your computer and use it in GitHub Desktop.
/**
JSONPrimitive represents any Swift type which can be interchanged with a primitive
JSON type. Use this protocol instead of `Any` when dealing with JSON data.
*/
public protocol JSONPrimitive {}
/**
Int is excluded here because JSON only has one "type" for numbers,
so we always use Double to avoid lossy conversion.
*/
extension String: JSONPrimitive {}
extension Double: JSONPrimitive {}
extension Bool: JSONPrimitive {}
extension Dictionary: JSONPrimitive where Key == String, Value: JSONPrimitive {}
extension Array: JSONPrimitive where Element: JSONPrimitive {}
extension Optional: JSONPrimitive where Wrapped: JSONPrimitive {}
// A JSONValue itself can act as a JSONPrimitive!
extension JSONValue: JSONPrimitive { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment