Saving Data in iOS · JSON | Ray Wenderlich


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/6307-saving-data-in-ios/lessons/10

Hi,

may I have a question?
Do I have to remove the custom init() from the Image struct when writing an Array extension?
You did it in the video, I forgot to do it and still everything works as expected, but I don’t know how that’s possible.
When running let images = try [Image](filename: "images") the custom init() from my Array extension decodes the JSON file to a type ‘array of Images’, right? BUT, when filling the new array with Images, it needs to create several individual instances of Image structure and while doing so, it should call the Image initializer for each of those instances. But, that should not be possible, because I didn’t remove my custom init() from Image structure and it requires a file name as a parameter, therefore it should fail while creating the new Image object…
Could you please explain to me how is that possible?
Thank You

Do I have to remove the custom init() from the Image struct when writing an Array extension?

No. We just never use it again in the course.

When running let images = try [Image](filename: "images") the custom init() from my Array extension decodes the JSON file to a type ‘array of Images’, right?

Right.

BUT, when filling the new array with Images, it needs to create several individual instances of Image structure and while doing so, it should call the Image initializer for each of those instances.

Swift requires that an initializer get called, but you don’t use it directly. It’s generated for you when you use Decodable.

But, that should not be possible, because I didn’t remove my custom init() from Image structure and it requires a file name as a parameter, therefore it should fail while creating the new Image object…
Could you please explain to me how is that possible?

The initializers are unrelated. Let me know if you still have any questions!

OK, so Swift automatically creates a new initializer to conform to the Decodable protocol, is that correct?
Now everything makes sense, thank you for the explanation!

1 Like

You’ve got it. Search for init(from decoder: Decoder) on this page, and you’ll see what it looks like.