Skip to content

Instantly share code, notes, and snippets.

@MojtabaHs
Last active August 5, 2020 08:19
Show Gist options
  • Save MojtabaHs/9ed1d02bcba3cb3e1db44523e3a8efc8 to your computer and use it in GitHub Desktop.
Save MojtabaHs/9ed1d02bcba3cb3e1db44523e3a8efc8 to your computer and use it in GitHub Desktop.
A PropertyWrapper for load and decode any Decodable from the given bundle.
@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