Skip to content

Instantly share code, notes, and snippets.

@atheken
Created November 12, 2015 14:53
Show Gist options
  • Save atheken/bc5aeff753fdbf64ddef to your computer and use it in GitHub Desktop.
Save atheken/bc5aeff753fdbf64ddef to your computer and use it in GitHub Desktop.
Super lazy JSON lookups.
struct Jawn {
let value:AnyObject?
var string:String? { return self.value as? String }
var int:Int? { return self.value as? Int }
var double:Double? { return self.value as? Double }
var array:[Jawn]? { return (self.value as? NSArray)?.map{Jawn($0)} }
var bool:Bool? { return self.value as? Bool }
var dictionary:[String:Jawn]? {
guard let dictionary = self.value as? NSDictionary else {
return nil
}
var retval = Dictionary<String,Jawn> ();
for (_, pair) in dictionary.enumerate() {
retval[pair.key as! String] = Jawn(pair.value)
}
return retval
}
init(_ value: AnyObject?) {
self.value = value
}
subscript(index:Int) -> Jawn {
guard let arr = self.value as? NSArray where arr.count > index else {
return Jawn(nil)
}
return Jawn(arr.objectAtIndex(index))
}
subscript(key:String) -> Jawn {
guard self.value != nil else {
return self
}
guard let dictionary = self.value as? NSDictionary else {
return Jawn(nil)
}
return Jawn(dictionary[key])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment