Created
August 8, 2020 11:49
-
-
Save trilliwon/642c67f034f58cf190dc3d6b22746b1f to your computer and use it in GitHub Desktop.
decode json file
This file contains hidden or 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
extension Bundle { | |
func decode<T: Decodable>(_ type: T.Type, from file: String) -> T { | |
guard let url = 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() | |
do { | |
return try decoder.decode(T.self, from: data) | |
} catch { | |
fatalError("Failed to decode \(file) from bundle. error: \(error.localizedDescription)") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment