Skip to content

Instantly share code, notes, and snippets.

@NikolajMosbaek
Created April 27, 2022 11:44
Show Gist options
  • Save NikolajMosbaek/610292063a512fa0374d794728064e38 to your computer and use it in GitHub Desktop.
Save NikolajMosbaek/610292063a512fa0374d794728064e38 to your computer and use it in GitHub Desktop.
A universal way to decode a bundle
extension Bundle {
func decode<T: Decodable>(_ file: String) -> T {
guard let url = self.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()
guard let loaded = try? decoder.decode(T.self, from: data) else {
fatalError("Failed to decode \(file) from bundle.")
}
return loaded
}
}
@NikolajMosbaek
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment