Created
July 11, 2022 11:13
-
-
Save D-Antonelli/3f45b0e93b6931c96c405f3edf69aee1 to your computer and use it in GitHub Desktop.
JSON Date Formatter
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<T: Decodable>(_ file: String) -> 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) in bundle") | |
} | |
let decoder = JSONDecoder() | |
let formatter = DateFormatter() | |
formatter.dateFormat = "y-MM-dd" | |
decoder.dateDecodingStrategy = .formatted(formatter) | |
guard let loaded = try? decoder.decode(T.self, from: data) else { | |
fatalError("Failed to decode \(file) in bundle") | |
} | |
return loaded | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment