Last active
September 15, 2020 19:01
-
-
Save glenngijsberts/ef00bb458faae24541b3e0c48c250d55 to your computer and use it in GitHub Desktop.
Interesting code snippet from Day 39 of #100DaysOfSwiftUI
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
// | |
// Bundle-Decodable.swift | |
// Moonshot | |
// | |
// Created by Glenn Gijsberts on 13/09/2020. | |
// Copyright © 2020 Glenn Gijsberts. All rights reserved. | |
// | |
import Foundation | |
extension Bundle { | |
func decode<T: Codable>(_ 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) from 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) from bundle") | |
} | |
return loaded | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment