Skip to content

Instantly share code, notes, and snippets.

@keremk
Created January 12, 2020 10:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keremk/92d436a055aa4a877237574fc804e607 to your computer and use it in GitHub Desktop.
Save keremk/92d436a055aa4a877237574fc804e607 to your computer and use it in GitHub Desktop.
func fetchPreviewData<T: Decodable>(previewFile: String, fetcher: () -> T) -> T {
#if PREVIEW
return loadPreviewData(previewFile)
#else
return fetcher()
#endif
}
#if PREVIEW
// Below is directly "borrowed" from https://developer.apple.com/tutorials/swiftui/composing-complex-interfaces
func loadPreviewData<T: Decodable>(_ filename: String) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}
do {
let decoder = useDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment