Created
August 2, 2024 11:44
-
-
Save vincent-peng/7c91f2e1b166978ad14facf60d2840b4 to your computer and use it in GitHub Desktop.
Swift JSON Loader
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
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