Last active
November 6, 2023 19:20
-
-
Save StewartLynch/a84b4ddbeaf5a78e94bfe604ff7c7d7d to your computer and use it in GitHub Desktop.
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
extension Bundle { | |
public func decode<T: Decodable>(_ type: T.Type, | |
from file: String, | |
dateDecodingStategy: JSONDecoder.DateDecodingStrategy = .deferredToDate, | |
keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys) -> T { | |
guard let url = self.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() | |
decoder.keyDecodingStrategy = keyDecodingStrategy | |
decoder.dateDecodingStrategy = dateDecodingStategy | |
guard let decodedData = try? decoder.decode(T.self, from: data) else { | |
fatalError("Failed to decode \(file) from bundle.") | |
} | |
return decodedData | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment