Skip to content

Instantly share code, notes, and snippets.

@grago
Created December 14, 2018 06:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grago/bd31b9d707efbe9e0a6ce20acc25ce29 to your computer and use it in GitHub Desktop.
Save grago/bd31b9d707efbe9e0a6ce20acc25ce29 to your computer and use it in GitHub Desktop.
[Extension - Decoding JSON from your bundle] #ios #swift
extension Bundle {
func decode<T: Decodable>(_ type: T.Type, from filename: String) -> T {
guard let json = url(forResource: filename, withExtension: nil) else {
fatalError("Failed to locate \(filename) in app bundle.")
}
guard let jsonData = try? Data(contentsOf: json) else {
fatalError("Failed to load \(filename) from app bundle.")
}
let decoder = JSONDecoder()
guard let result = try? decoder.decode(T.self, from: jsonData) else {
fatalError("Failed to decode \(filename) from app bundle.")
}
return result
}
}
let items = Bundle.main.decode([TourItem].self, from: "Tour.json")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment