Skip to content

Instantly share code, notes, and snippets.

@sergiosette
Created January 2, 2018 08:11
Show Gist options
  • Save sergiosette/ce4f67fdf7af8e98cad50e012be75e6b to your computer and use it in GitHub Desktop.
Save sergiosette/ce4f67fdf7af8e98cad50e012be75e6b to your computer and use it in GitHub Desktop.
public enum JSONValue {
case string(String)
case int(Int)
case double(Double)
case bool(Bool)
case object([String: JSONValue])
case array([JSONValue])
}
extension JSONValue: Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .string(let string): try container.encode(string)
case .int(let int): try container.encode(int)
case .double(let double): try container.encode(double)
case .bool(let bool): try container.encode(bool)
case .object(let object): try container.encode(object)
case .array(let array): try container.encode(array)
}
}
}
extension JSONValue {
func jsonString(file: StaticString = #file, line: UInt = #line) -> String {
do {
guard let value = try String(data: JSONEncoder().encode(self), encoding: .utf8) else {
fatalError("Error in test data! String could not be parsed from data", file: file, line: line)
}
return value
} catch {
fatalError("Error in test data! \(error.localizedDescription)", file: file, line: line)
}
}
}
extension JSONValue: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self = .string(value)
}
}
extension JSONValue: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) {
self = .int(value)
}
}
extension JSONValue: ExpressibleByFloatLiteral {
public init(floatLiteral value: Double) {
self = .double(value)
}
}
extension JSONValue: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = .bool(value)
}
}
extension JSONValue: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: JSONValue...) {
self = .array(elements)
}
}
extension JSONValue: ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (String, JSONValue)...) {
self = .object([String: JSONValue](uniqueKeysWithValues: elements))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment