Something I havent figured out or have been able to find online as of yet.
Is there a way to add additional fields onto a struct containing the decodable protocol in which are not present in the JSON Data?
For example and simplicity, say I have an array of json objects structured as such
{ "name": "name1", "url": "www.google.com/randomImage" }
but say I want to add a UIImage variable to that struct containing the decodable such as
struct Example1: Decodable {
var name: String?
var url: String?
var urlImage: UIImage? //To add later
}
Is there a way to implement the decodable protocol in order to get the name and url from the JSON but allow me to add the UIImage later?
To exclude
urlImageyou must manually conform toDecodableinstead of letting its requirements be synthesized:Before Swift 4.1 this only works if you add
= niltourlImage, even though the default value ofnilis usually assumed for optional properties.If you want to provide a value for
urlImageat initialization, rather than using= nil, you can also manually define the initializer: