Created
April 27, 2022 11:44
-
-
Save NikolajMosbaek/610292063a512fa0374d794728064e38 to your computer and use it in GitHub Desktop.
A universal way to decode a bundle
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>(_ 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() | |
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
// From 100 Days of SwiftUI (Day 40) by Paul Hudson: https://www.hackingwithswift.com/books/ios-swiftui/using-generics-to-load-any-kind-of-codable-data