Created
January 12, 2020 10:48
-
-
Save keremk/92d436a055aa4a877237574fc804e607 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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