Skip to content

Instantly share code, notes, and snippets.

@mackoj
Created May 19, 2022 14:08
Show Gist options
  • Save mackoj/25df45ac4ee0c069958a71d17c5ac263 to your computer and use it in GitHub Desktop.
Save mackoj/25df45ac4ee0c069958a71d17c5ac263 to your computer and use it in GitHub Desktop.
Decode file from bundle
import Foundation
extension Bundle {
func decode<Output: Decodable>(
_ type: Output.Type,
filename: String,
withExtension ext: String,
decoder: any TopLevelDecoder = JSONDecoder()
) throw -> Output {
guard let fileURL = url(forResource: filename, withExtension: ext) else {
fatalError("Failed to locate \(filename).\(ext) in \(self.bundleURL.absoluteString).")
}
let fileData = try Data(contentsOf: fileURL)
return try decoder.decode(Output.self, from: fileData)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment