Extending JSONObject with some Convenience
I have become quite fond of the JSON mapping approach in No-Magic JSON Parsing with Swift Part 2 and extended it with the following convenience method.
extension JSONObject {
/// Returns a JSON object initialized by reading into it the data from the file specified by a given path.
/// - Parameter path: The absolute path of the file from which to read data.
/// - Returns: A JSON object initialized by reading into it the data from the file specified by path.
convenience init?(contentsOfFile path: String) {
guard let data = NSData(contentsOfFile: path),
json = (try? NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)) as? [String : AnyObject] else { return nil }
self.init(dictionary: json)
}
}
You can also find on GitHub as a Gist