Created
October 5, 2019 00:47
-
-
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
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
// | |
// 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