Created
May 19, 2022 14:08
-
-
Save mackoj/25df45ac4ee0c069958a71d17c5ac263 to your computer and use it in GitHub Desktop.
Decode file from bundle
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
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