0
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) in Bundle")
        }

        let decoder = JSONDecoder()

        guard let decodedData = try? decoder.decode(T.self, from: data) else {
            fatalError("Failed to decode \(file) in Bundle")
        }

        return decodedData
    }
}

I am still getting my feet wet in swiftui and app development, above is my codable bundle extension, how do i add a urlsession to it or better yet with combine. Thanks

vadian
  • 274,689
  • 30
  • 353
  • 361
EMPIRE
  • 57
  • 7
  • 1
    Unrelated but this is Hacking-with-Swift’s Bundle extension. Better use [this one](https://www.hackingwithswift.com/example-code/system/how-to-decode-json-from-your-app-bundle-the-easy-way), it catches DecodingErrors properly. You don’t need a network request to read a local file. – vadian Jun 23 '21 at 08:49
  • You can take a reference from here : https://stackoverflow.com/a/68062904/14733292 if you're using swift 5.5 then you can check this too https://stackoverflow.com/q/68086461/14733292 – Raja Kishan Jun 23 '21 at 08:55

0 Answers0