Created
December 14, 2018 06:32
-
-
Save grago/bd31b9d707efbe9e0a6ce20acc25ce29 to your computer and use it in GitHub Desktop.
[Extension - Decoding JSON from your bundle] #ios #swift
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
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