Created
August 5, 2021 17:00
-
-
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
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
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