The first time I know I can define a struct within a function body, I was quite surprised. Why the hell I want to do such annoying thing?

For naming scope? No, I can only use it in my function scope.

For better segregate the logic? Maybe, but still, I can’t understand why it’s better to do it inside a function since even a nested type should be fine of doing so.

Until, until Swift4 is out, and the convenience Codable it out.

Codable is not new, but extremely helpful for rapid develop with restful service. Since JSON almost rule all the mobile server communication nowadays, we heavily rely on it to make network request.

And we have:

In the same time, the JSON format are usually predictably unpredictable, especially when a rapid iteration is required for modern development environment, the model we want to match the server will change across time which can make version control a nightmare.


But we are developer, we are used to been through any kind of storm, we don’t afraid challenge. In development 101, we leant how to use different layer to decouple our implementation so that we can face changes in cool. Therefore, we may want to have a so far comparably stable version of Local Model in our business layer and hopefully, all the small iteration’s functionality won’t get much changes, only the way our server developer return data are getting improved day by day…

Therefore, we decided not to change our local model any more, we want our liberty on how to do the client end right!

Then we should give up Codable? No! So we will have lot of:

to free our hand but still can be backward compatible… But having the ugly lovely thing at the global name space? Please kill me.

This is when a in function struct come to save us:

Sometime, we need some trade off to achieve some goal, even though the ugly naming struct can help us to segregate the data model from the server response, it’s still not some good thing to fly around the whole system. Sometime, we want to have some convenient one shoot model to help us shorten the time to decode an data structure, this could be one reason, the ability to define a in function type is helpful. We can hide our messy stuff inside the body but still take the advantage to isolate the data structure/ logic or save time.

And that’s it. Thanks for watching.