Skip to content

Instantly share code, notes, and snippets.

@trilliwon
Created August 8, 2020 11:49
Show Gist options
  • Save trilliwon/642c67f034f58cf190dc3d6b22746b1f to your computer and use it in GitHub Desktop.
Save trilliwon/642c67f034f58cf190dc3d6b22746b1f to your computer and use it in GitHub Desktop.
decode json file
extension Bundle {
func decode<T: Decodable>(_ type: T.Type, from file: String) -> T {
guard let url = url(forResource: file, withExtension: nil) else {
fatalError("Failed to locate \(file) in bundle.")
}
guard let data = try? Data(contentsOf: url) else {
fatalError("Failed to load \(file) from bundle.")
}
let decoder = JSONDecoder()
do {
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Failed to decode \(file) from bundle. error: \(error.localizedDescription)")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment