Skip to content

Instantly share code, notes, and snippets.

@asaday
Created May 24, 2017 16:00
Show Gist options
  • Save asaday/5718e05cefdb0706c8e031f3ce4578a6 to your computer and use it in GitHub Desktop.
Save asaday/5718e05cefdb0706c8e031f3ce4578a6 to your computer and use it in GitHub Desktop.
extension NSDictionary {
func lastof(path: String) -> Any? {
var r: NSDictionary? = self
let ar = path.components(separatedBy: "/")
for a in ar.dropLast() {
if a.isEmpty { continue }
r = r?[a] as? NSDictionary
if r == nil { return nil }
}
guard let last = ar.last else { return nil }
return r?[last]
}
func string(path: String) -> String? { return lastof(path: path) as? String }
func array(path: String) -> NSArray? { return lastof(path: path) as? NSArray }
func dictionary(path: String) -> NSDictionary? { return lastof(path: path) as? NSDictionary }
func int(path: String) -> Int? {
let r = lastof(path: path)
if let s = r as? String { return Int(s) }
return r as? Int
}
func bool(path: String) -> Bool? {
let r = lastof(path: path)
if let s = r as? String { return s.lowercased() == "true" || Int(s) != 0 }
return r as? Bool
}
var jsonData: Data? { return try? JSONSerialization.data(withJSONObject: self, options: []) }
var jsonString: String? {
guard let d = jsonData else { return nil }
return String(data: d, encoding: .utf8)
}
}
public extension Data {
var json: Any? { return (try? JSONSerialization.jsonObject(with: self, options: .allowFragments)) }
var jsonDictionary: NSDictionary? { return json as? NSDictionary }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment