Skip to content

Instantly share code, notes, and snippets.

@qmchenry
Created August 5, 2021 17:00
Show Gist options
  • Save qmchenry/bc987227a8550b715390fb9cc5536335 to your computer and use it in GitHub Desktop.
Save qmchenry/bc987227a8550b715390fb9cc5536335 to your computer and use it in GitHub Desktop.
Decodable instantiation from an asset catalog Data Set to help with SwiftUI Previews
import UIKit
extension NSDataAsset {
/// Load a data asset from a catalog and try decoding it to a specific Decodable type
/// - Returns: An optional instance of type T decoded from the named data asset
/// Usage: `NSDataAsset.decode(DocodableThing.self, asset: "my thing")`
public static func decode<T>(_ type: T.Type, asset name: String) -> T? where T: Decodable {
guard let asset = Self(name: name) else { return nil }
return try? JSONDecoder().decode(T.self, from: asset.data)
}
}
extension Decodable {
/// Optional initializer from JSON data stored in an asset catalog
/// - Parameter name: the string name of an asset in a catalog
/// - Returns: Optional instance of a decodable from the JSON data stored in the asset catalog
/// Usage: `DecodableThing(asset: "my thing")`
public init?(asset name: String) {
guard let me = NSDataAsset.decode(Self.self, asset: name) else { return nil }
self = me
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment