Skip to content

Instantly share code, notes, and snippets.

@alexpaul
Last active July 24, 2020 19:43
Show Gist options
  • Save alexpaul/0c2d019a725d27020972b58e41085cce to your computer and use it in GitHub Desktop.
Save alexpaul/0c2d019a725d27020972b58e41085cce to your computer and use it in GitHub Desktop.
Generic function to parse local JSON from either a dictionary or array structure. Bundle. JSON. Parsing.
extension Bundle {
enum BundleError: Error {
case noResource(String)
case noContents(String)
case decodingError(Error)
}
func parseJSONData<T: Decodable>(_ name: String, ext: String = "json") throws -> T {
guard let path = Bundle.main.path(forResource: name, ofType: ext) else {
throw BundleError.noResource(name)
}
guard let data = FileManager.default.contents(atPath: path) else {
throw BundleError.noContents(path)
}
var elements: T
do {
elements = try JSONDecoder().decode(T.self, from: data)
} catch {
throw BundleError.decodingError(error)
}
return elements
}
}
// Usage
// dictionary
do {
let wrapper: ContactsWrapper = try Bundle.main.parseJSONData("contacts")
dump(wrapper)
} catch {
dump(error)
}
// array
do {
let wrapper: [Weather] = try Bundle.main.parseJSONData("weather")
dump(wrapper)
} catch {
dump(error)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment