Skip to content

Instantly share code, notes, and snippets.

@NinoScript
Created October 23, 2015 04:03
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 NinoScript/12f744f67dcfc3d28bc9 to your computer and use it in GitHub Desktop.
Save NinoScript/12f744f67dcfc3d28bc9 to your computer and use it in GitHub Desktop.
import Cocoa
// My JSON Framework
protocol NinoScriptJSON {
init(json:String) throws
init(any:AnyObject) throws
}
extension NinoScriptJSON {
init(json:String) throws {
let data = json.dataUsingEncoding(NSUTF8StringEncoding)!
let deserialized = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
try self.init(any:deserialized)
}
}
enum JsonError: ErrorType {
case error
}
// Models
struct A {
let i:Int
}
struct B {
let s:String
let a:A
}
struct C {
let o:Int?
let v:Int?
let n:Int?
}
// Models extensions with the framework
extension A:NinoScriptJSON {
init(any: AnyObject) throws {
guard
let dict = any as? [String:AnyObject],
let i = dict["i"] as? Int
else { throw JsonError.error }
self.i = i
}
}
extension B:NinoScriptJSON {
init(any: AnyObject) throws {
guard
let dict = any as? [String:AnyObject],
let a = dict["a"],
let s = dict["s"] as? String
else { throw JsonError.error }
self.a = try A(any: a)
self.s = s
}
}
extension C:NinoScriptJSON {
init(any: AnyObject) throws {
guard
let dict = any as? [String:AnyObject]
else { throw JsonError.error }
if let o = dict["o"] as? Int? {
self.o = o
} else {
self.o = nil
}
if let v = dict["v"] as? Int? {
self.v = v
} else {
self.v = nil
}
if let n = dict["n"] as? Int? {
self.n = n
} else {
self.n = nil
}
}
}
// Data
let i = 123
let s = "a"
// JSON Strings
let a = "{\"i\":\(i)}"
let b = "{\"s\":\"\(s)\", \"a\":\(a)}"
let c = "{\"o\":null, \"n\":555}"
// Models
let ma = try A(json: a)
let mb = try B(json: b)
let mc = try C(json: c)
// Tests
ma.i == i
mb.s == s
mb.a.i == i
mc.o
mc.n
mc.v
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment