-
Notifications
You must be signed in to change notification settings - Fork 119
JSON
Freddy
defines an enumeration called JSON
to encapsulate JSON data. Since JSON data is structured, and exclusive, an enumeration is a great mechanism for modeling this data.
Here is the definition for JSON
:
public enum JSON {
case array([JSON])
case dictionary([String: JSON])
case double(Double)
case int(Int)
case string(String)
case bool(Bool)
case null
}
The enumeration JSON
provides a case for all of the data types that JSON data encapsulates. Each case, with the exception of .null
, provides an associated value so that it can carry with it the anticipated data.
The cases for .array
and .dictionary
have more complex associated values that can themselves carry with them instances of JSON
. After all, a JSON array may contain dictionaries as its elements.
In the parlance of Freddy
, this would be a JSON
instance set to the case .array
whose associated value is [.dictionary]
. The .dictionary
would then have String
keys and JSON
values, which would typically be .double
, .int
, .string
, or .bool
.
In the file JSONLiteralConveritble.swift
, Freddy
provides a number of extensions wherein JSON
conforms to several LiteralConvertible
protocols. This allows for code like this:
let json = ["results": [
["name": "Matt Mathias", "age": 32],
["name": "Drew Mathias", "age": 33]
]
] as JSON
or
let json: JSON = ["results": [
["name": "Matt Mathias", "age": 32],
["name": "Drew Mathias", "age": 33]
]
]
// where json is:
// JSON.dictionary([String: .array(.dictionary([String: .int(Int)]))])
Thus, json
represents a simple example of some JSON payload you may receive from calling a web service.
You can also create JSON
literals like so:
let jsonBool: JSON = false // JSON.bool(false)
let jsonString: JSON = "Freddy!" // JSON.string("Freddy!")
let jsonInt: JSON = 13 // JSON.int(13)
Created by Big Nerd Ranch 2015