Last active
July 24, 2020 19:43
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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