Last active
December 15, 2020 21:41
-
-
Save juliaYamamoto/e1bdddb8be40b86454077dc79c4ffa74 to your computer and use it in GitHub Desktop.
Parse a local json using generics
This file contains 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
// Static function to decode a local json | |
// Receives a path and a generic type (must conform to the codable protocol) and return the data decoded into the given type | |
class JsonParser { | |
static func from<T: Codable> (path: String, ofType: T.Type) -> T? { | |
guard let jsonPath = Bundle.main.path(forResource: path, ofType: "json") else { return nil } | |
do { | |
guard let jsonData = try String(contentsOfFile: jsonPath).data(using: .utf8) else { | |
return nil | |
} | |
let decodedData = try JSONDecoder().decode(ofType.self, from: jsonData) | |
return decodedData | |
} catch { | |
print(error) | |
return nil | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment