Some girls.

Some girls have a way of making you do everything you know you shouldn’t.. “Some girls.” is published by completely sideways, man.

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Fast models creation by using code generation in swift

Hello, everyone!

Today we are going to learn how to stop writing boilerplate code.

We are always write the same code when create some model. Let’s imagine, that we are have the place, which have the id, name and location. So our struct will look something like this:

The projects have many similarly looking models. At the same time, we spend a lot of time to write the same boilerplate code.

We need to create new Run Script Phase in xcode like this:

Then when you will “Build” your project, sourcery will generate code for all your templates.

Let’s create the new folder in our xcode project with name: “Templates” and our models should be in the folder with name “Models”.

Now we need to create “.sourcery.yml” file in our project folder. And write this:

You have to replace “ProjectName” with your Project name (folder name), so it’s the path to our models folder and templates from “.sourcery.yml” file.

So now all is ready to generate code. We just need to create a template. Let’s create simple “JSONAutoRepresentable” protocol:

In the Templates folder, which we’ve created recently create file “JSONRepresentable.stencil”

Ok, now we need to write our template. What we have to do?

2. Our model can have some variables, which is not came from the server. In this case we can add annotation: “//sourcery: skip” for this variable and then we have to go through all variable, which doesn’t have skip annotation:

3. In some cases we can have the different variable name and json key. In this case we can mark this variable with “//sourcery: jsonKey = “JSONKey””. Then:

4. If the variable is Array, then we need to map to elementsTypes (and we need to convert camel case to snake case.):

5. If the variable is a JSONAutoRepresenteable as well:

6. If the variable is a enum:

7. And for all other variables:

The full JSONRepresentable.stencil file you can find here:

So now we can add JSONAutoRepresentable protocol to our Place model and build project. Here is a result:

And here is a example of model with skip annotation and jsonKey:

You can read more about templates here:

Hope this article was helpful for you. ✌️

Add a comment

Related posts:

Nature Poem

Blossoming Blooming Beauty. “Nature Poem” is published by Melissa Rios in El Sereno Community Garden.

Mothers

She struggled and fumbled in her pouch for her token. She must have accidentally dropped it when she found her pouch momentarily unzipped outside a cafe. Instead and finally, her phone finished…