Skip to content

Instantly share code, notes, and snippets.

@yanil3500
Created October 5, 2019 00:47
Show Gist options
  • Save yanil3500/d49d095d4fde579cf4495855945ac595 to your computer and use it in GitHub Desktop.
Save yanil3500/d49d095d4fde579cf4495855945ac595 to your computer and use it in GitHub Desktop.
[Bundle JSON Extension] Extension for loading JSON from a Bundle #json #bundle #swift #ios
//
// Helper.swift
// A small collection of quick helpers to avoid repeating the same old code.
//
// Created by Paul Hudson on 23/06/2019.
// Copyright © 2019 Hacking with Swift. All rights reserved.
//
import UIKit
extension Bundle {
func decode<T: Decodable>(_ type: T.Type, from 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