Last active
August 5, 2020 08:19
-
-
Save MojtabaHs/9ed1d02bcba3cb3e1db44523e3a8efc8 to your computer and use it in GitHub Desktop.
A PropertyWrapper for load and decode any Decodable from the given bundle.
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
@propertyWrapper struct BundleFile<DataType> { | |
let name: String | |
let type: String | |
let fileManager: FileManager = .default | |
let bundle: Bundle = .main | |
let decoder: (Data) -> DataType | |
var wrappedValue: DataType { | |
guard let path = bundle.path(forResource: name, ofType: type) else { fatalError("Resource not found") } | |
guard let data = fileManager.contents(atPath: path) else { fatalError("File not loaded") } | |
return decoder(data) | |
} | |
} | |
// MARK: Examples | |
struct Example { | |
@BundleFile(name: "avatar", type: "jpg", decoder: { UIImage(data: $0)! } ) | |
var avatar: UIImage | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment