Skip to content

Instantly share code, notes, and snippets.

@vincent-peng
Created August 2, 2024 11:44
Show Gist options
  • Save vincent-peng/7c91f2e1b166978ad14facf60d2840b4 to your computer and use it in GitHub Desktop.
Save vincent-peng/7c91f2e1b166978ad14facf60d2840b4 to your computer and use it in GitHub Desktop.
Swift JSON Loader
func load<T: Decodable>(_ filename: String) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment