<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yura Privezentsev on Medium]]></title>
        <description><![CDATA[Stories by Yura Privezentsev on Medium]]></description>
        <link>https://medium.com/@privezentsev?source=rss-a589e9862836------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*BykVhmxhSjqgoAx0</url>
            <title>Stories by Yura Privezentsev on Medium</title>
            <link>https://medium.com/@privezentsev?source=rss-a589e9862836------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:55:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@privezentsev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Modularity lifehacks on iOS]]></title>
            <link>https://medium.com/hh-ru/modularity-lifehacks-on-ios-f52ec54f452e?source=rss-a589e9862836------2</link>
            <guid isPermaLink="false">https://medium.com/p/f52ec54f452e</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[tuist]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Yura Privezentsev]]></dc:creator>
            <pubDate>Tue, 21 Jun 2022 06:03:28 GMT</pubDate>
            <atom:updated>2022-06-21T06:03:28.516Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, everyone! My name is Yura and I’m an iOS-developer in core-team at hh.ru. In this article I’m going to talk about how we work with multiple modules in our iOS-apps. We’ll discuss the environment and structure of our project, touch the topic of build time and dive into code generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WBC7jvEFSV2FgGgeB1SnjA.jpeg" /></figure><h4><strong>Our team and projects</strong></h4><p>Our core-team is responsible for making it convenient to work on the app for other iOS teams. We create automations, improve codebase and refactoring and so on.</p><p>Currently we’re working on two applications: for applicants and employers. 10 iOS developers are working on both projects, and we’re distributed between 5 teams in the mobile department. In order to make simultaneous work comfortable, we split our app into multiple modules or features.</p><p>In our terminology feature is a separate Xcode project with its own isolated code and everything needed like resources or texts and which is connected to other features and the main app. Thanks to such a feature division we provide possibility for independent work in each team.</p><p>In 2018 our application was a huge monolith piece of code, poorly divided into four barely independent, but still interrelated parts. Lately we’ve been cracking and dragging these parts, so now the monolith looks much smaller. As for new features, we make them all isolated. Nowadays there exists 75 independent features in our app, it has become some kind of a container ship which carries a lot of container features.</p><p>But with the division came the problems. In the article I’m going to thoroughly describe the following:</p><p><strong>Firstly,</strong> such a huge number of features is difficult to support in the app: you need to follow the coherent structure and networks between them.</p><p><strong>Secondly</strong>, our project is really big. As it consists of a great amount of lines of code, the compilation takes a lot of time.</p><p><strong>Thirdly, </strong>a big project is hard to<strong> </strong>maintain due to the<strong> </strong>tremendous number of agreements and relations between features. In a nutshell, the size of the project complicates the development.</p><h4><strong>Problem 1: Project structure support</strong></h4><p>As it naturally comes, a huge number of xcode projects are difficult to manage. You must have faced the conflicts of xcodeproj files while merging. Most of the time they are solved pretty easily. Nevertheless, if they appear quite often, it becomes annoying to waste time on them.</p><p>As the app consists of many independent features, their support can be difficult. While managing projects in Xcode interface you can change some projects, but easily miss or forget to add something to others. That’s why we started looking for the source of the problem right away.</p><p>At first we used <a href="https://cocoapods.org/">CocoaPods</a> — popular dependency manager. We realized that we could build our multi-module architecture via applying development pods to our features. Inner projects for CocoaPods are written as a special podspec file. It’s smaller than the Xcode project description and contains only the main information.</p><p>However, with growing project we started to encounter more and more problems and restrictions from CocoaPods.</p><p>For example, CocoaPods forbids its simultaneous work with Swift Package Manager and Carthage for external dependencies. At some point it became a serious problem for us. Plus, CocoaPods is quite tricky about cashing dependencies.</p><p>We started contemplating leaving Cocoapods, but we need to decide where to go and what other tools we could use for external dependencies. As a result of our thorough search, we came across <a href="https://tuist.io/">Tuist</a>. It’s a utility which generates and supports Xcode-project.</p><p>Project description with Tuist looks something similar to package description for SPM but supports nearly all settings of xcodeproj. Thanks to Tuist, our project description has become even easier for comprehension.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a7c2a43a1dffc0bba0ea82a8124f350/href">https://medium.com/media/8a7c2a43a1dffc0bba0ea82a8124f350/href</a></iframe><p>We hid all the meta information which could be found in other sources, and left only the most important things. It comes down to mentioning the name of the feature, which resources should be generated for it with <a href="https://github.com/SwiftGen/SwiftGen">SwiftGen</a> and what targets it has. The lists of dependencies are formed automatically for each target. It is done with the help of the script that looks for all import in the target’s files. The writing of the project got easier, and the process became more comfortable.</p><p>While we were moving from CocoaPods to Tuist, we noticed that the location of our project’s files was quite peculiar due to some historical reasons and God-knows-what else. To avoid repeating the action twice, we cleared the structure of the project and arranged everything, so now it lies in the right folders. That was what the developers thanked us for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OvfoQj_hrI2JSu6A4uWeig.jpeg" /></figure><h4><strong>Problem 2: Slow compilation</strong></h4><p>At some point the developers noticed that project build took around five minutes. That became a huge problem, as they got distracted during that time and fell out of the loop, switching to other tasks. That’s why a lot of time was wasted on diving into the work again.</p><p>We started thinking how we could fix that and decided to begin with gathering honest statistics on how much time is spent on our projects’ compilation. That’s where <a href="https://github.com/MobileNativeFoundation/XCLogParser">XCLogParser</a> came to our rescue. Xcode presents reports after build in xcactivitylog format. These reports contain all the information about the build, including each file. At the same time, XCLogParser can parse all these reports into a format which is easier to understand for an ordinary human. For example, reflect it visually or in json format.</p><p>Here’s an example of json, which is presented by XCLogParser after report analysis. The line that interests us is the time spent on the project compilation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2I0uE2gSnr2wNHNnOG38Xg.png" /></figure><p>Nevertheless, this json is actually enormous and it contains the most detailed information possible about each step of project build. This is what really excites us! We take all this information and send it to our database. There we use it to create beautiful graphics about the time spent on project build in <a href="https://grafana.com/">Grafana</a>. That’s what graphics for apps look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*chIfav-plylJr07C7dB3ZA.png" /></figure><p>They’re going up and down, but it’s ok, because currently we have two different types of machines on CI: processors Intel and M1. The machines on M1 build a project faster, of course. We don’t just look at these graphics; they help us find problems in the configuration of our projects. You can find more details on changing the speed of build in <a href="https://medium.com/hh-ru/build-time-in-ios-56bbc15c9c8f">this article</a>.</p><h4><strong>Environment setup</strong></h4><p>An obvious point. If a buggy commit got into the repository, this bug should be reproduced similarly: both in the developers’ mac and on CI. Therefore, if the bug is fixed, the fix should work on all devices too, the developers’ and CI.</p><p>This leads us to the idea that the project’s environment should be reproducible and unified, so that there are no true stories, when somebody complains in the chat about having a bug and the app build is screwed, whereas the guy on the other end replies: “WORKSFORME”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ei5dWP57634lp_g6S6xDsQ.jpeg" /></figure><p>In order to avoid such situations, we have a little lifehack. For example, apart from the swift code and the app itself, our project consists of various tools like Ruby, Fastlane, Danger, app dependencies which we install via Carthage, and swift utilities installed via Mint.</p><p>If you install, set up and launch these things by yourself, you can die a little. It means that the developer has to keep in mind a bunch of tools and remember the sequences of their installation, so that nothing crashes. And what if you have to update something? A whole different story.</p><p>We’d come to the conclusion that we needed a unified script for setting up the whole environment. And we wrote it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d42298173759279369925858aec1050/href">https://medium.com/media/3d42298173759279369925858aec1050/href</a></iframe><p>It installs all the necessary dependencies step by step, configures the project’s environment and does everything possible so that the developers don’t waste their time on thinking about it. Now it’s possible to download the project’s repository, launch our Bootstrap-script, make some tea, and come back later to find that everything is open and ready for productive work. The true wonder of this tool is that all dependencies and tools of the project are written in the repository. Simply put, the repository becomes the one and only source of truth. And this is very convenient — you can install and set up all this environment by using just one command.</p><h4><strong>Code generation</strong></h4><p>The next story is about code generation. One of the tools that we use — Xcode templates. I assume you’re already familiar with them. There are lots of useful articles on Xcode templates on the Internet, and they do their thing pretty well. The only drawback is a sophisticated configuration process. If you add different conditions when generating the template, it becomes twice as more complicated. And it has a disgusting syntax. Well, you know.</p><p>Nevertheless, Xcode templates are pretty good for some small groups and separate files. They’re convenient and available right from the standard Xcode menu. This allows it to stay in one app, not to fall out from the context and create small files quickly. Our project has some templates for such purposes, like for MVVM modules. Also there is a set of small templates for generating models, analytics and view files, design systems and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*suwtb1TPyvSNHOp11szOYA.png" /></figure><p>The next tool is again Tuist. It offers a <a href="https://docs.tuist.io/commands/scaffold">command</a> for file generation — scaffold. It’s rather convenient for creating big file groups and folder hierarchy. We use it for generating new features. A new blank feature actually contains a lot of code. It arranges the necessary folder hierarchy right away, so that the developer can generate everything necessary and move on to completing their task.</p><p>Here you can both create separate files via stencil templates, which should be in the content of this file. All in all, we have everything needed for creating a new feature.</p><p>Apart from that, we use SwiftGen in our project for generating code and access to different resources, for example to images and localization strings. For all the rest we use Sourcery which enables us to generate mocks for Unit-tests and other details on the project. So it saves us for real.</p><h4><strong>Conclusions</strong></h4><p>Tuist makes working with the project a lot easier: both in generation, and in new features’ creation. We constantly monitor the speed of the build, which allows us to spot the problems as soon as they appear. We try not to build the whole project at once: we assemble only the most necessary parts, thanks to the idea of splitting the project into features. Last but not least, we automate the development process and feature configuration, so that developers don’t waste time on such routines.</p><p>That’s all for now! Share with us your experience in working with big projects in the comments and feel free to ask any questions!</p><p><em>Sounds fun? Subscribe to our </em><a href="https://t.me/hh_tech_news"><em>news channel on telegram</em></a><em> and “</em><a href="https://www.youtube.com/channel/UCWztYdpQS3v9Gjno8bBZcNA"><em>HHella cool stories</em></a><em>” channel so you won’t miss new videos, articles, and other news. And you can ask our engineers any questions on any topic in the comments or in </em><a href="https://t.me/hh_tech"><em>hh developers’ telegram-chat</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f52ec54f452e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hh-ru/modularity-lifehacks-on-ios-f52ec54f452e">Modularity lifehacks on iOS</a> was originally published in <a href="https://medium.com/hh-ru">hh.ru</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build time in iOS]]></title>
            <link>https://medium.com/hh-ru/build-time-in-ios-56bbc15c9c8f?source=rss-a589e9862836------2</link>
            <guid isPermaLink="false">https://medium.com/p/56bbc15c9c8f</guid>
            <category><![CDATA[build-time]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Yura Privezentsev]]></dc:creator>
            <pubDate>Tue, 24 May 2022 06:03:22 GMT</pubDate>
            <atom:updated>2022-05-24T06:03:22.585Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qif6xFCE2hBNcdRu13ftGw.jpeg" /></figure><p>Hi there! My name is Yura and I’m an iOS-developer at hh.ru. In this article, we’ll touch on one of the most important metrics for iOS developers — build time. I’ll speak on how and why we collect build time metrics and what we do with them later.</p><p>Watch the video version <a href="https://www.youtube.com/watch?v=NJp_WqYrJ38">here</a>.</p><p><strong>What’s the problem with a long build?</strong></p><p>Long builds take you out of the task context that we’re working on. Knowing that the project will take a long time to build, you can afford to get distracted, go get a cup of coffee, and get caught up in chatting, and scrolling through social networks. And then 30 minutes later you remember that you were supposed to check on that bug instead of flipping through your Twitter feed or reading another Wikipedia article about anemones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E9cqhQoDH-1JfB49HpZddg.png" /></figure><p>So first, we’re going to figure out how to measure build time. After all, if we don’t know how bad it is, how will we know if it got better?</p><p><strong>How long does it take to build?</strong></p><p>There are two very simple ways to measure the time spent on the build directly in the Xcode interface. These are turning on the private setting <a href="https://stackoverflow.com/a/2801156">ShowBuildOperationDuration</a> and running the build through the menu Product -&gt; Perform Action -&gt; Build With Timing Summary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2NpRCpnPq0oZwqyLx1NsQ.png" /><figcaption>Build With Timing Summary in Xcode menu</figcaption></figure><p>In the first case, the final build time will be displayed in the Xcode status bar, and in the second case, we will get a mini-report on the different stages of the build, which can be viewed in Report Navigator. It displays the most interesting and complete build report available to us, but can we get it out of Xcode?</p><p><strong>Going into xcactivitylog</strong></p><p>The most detailed report on the build has the .xcactivitylog format. It’s in DerivedData, in the Logs folder. And it’s pretty complicated, but we have a <a href="https://www.youtube.com/watch?v=QVwOzfJIDCc">video</a> that explains how this format works. But don’t rush to roll up your sleeves and parse everything with your own hands, because it’s already been done for us.</p><p>There is <a href="https://github.com/MobileNativeFoundation/XCLogParser">XCLogParser</a> to parse these reports, which parses the reports and provides them to us in a convenient form for further work. For example, in the form of json, which is convenient to parse, or in html, which is convenient to view. The full list of formats is available <a href="https://github.com/MobileNativeFoundation/XCLogParser#reporters">here</a>.</p><p>Let’s take a closer look at the html report. Among other things, it gives us access to the build timeline of the whole project, as well as individual targets. And we can delve into each target and see the details. These timelines are incredibly cool because they let us see what project parts are holding up the entire build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wg1xnFmWtmYCEByFHxfdJQ.png" /><figcaption>Report fragment with a timeline</figcaption></figure><p>For example, in this part of the report, you can see that for a while we have been building only one target, the UI, on which all our product features depend. And at the same time, nothing else is build in parallel. In short, we are just wasting time.</p><p>This report also allows us to see in detail the process of compiling individual targets, files, build phases, and other phases of the project’s build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TIMIhX6qEg25V6WgyRwx-Q.png" /><figcaption>All application targets are listed by build time</figcaption></figure><p>And yeah, everything we see in such a report will also be available in json format, from which you can manually get everything you need.</p><p><strong>What are we collecting?</strong></p><p>We are currently collecting the following information on CI builds:</p><ul><li>Date</li><li>Build duration</li><li>Duration of individual phases</li><li>Application schema</li><li>Build configuration (debug, release, adHoc)</li><li>Clean build</li><li>Xcode version</li><li>Device model</li><li>User name</li><li>CI agent ID</li></ul><p>We receive most of this information from the report generated by XCLogParser, but we add little information about the system to understand in what environment the build took place in.</p><p><strong>Where and how do we store it?</strong></p><p>In our case, we use <a href="https://www.influxdata.com/">influxdb</a> to store data and <a href="https://grafana.com/">Grafana</a> to display graphs and reports.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZO0EMGMMSmsdTG6ruB89NQ.png" /></figure><p>Let’s work out what we can see in Grafana. We have a table with complete information on all the latest builds, where we can see all the data we were able to collect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bFGlEO7CMb4Er7Wz_Pg72w.png" /><figcaption>Latest Builds table</figcaption></figure><p>There is a separate schedule where we keep track of the duration of certain build phases, which we keep a special track of. For example, we keep track of the time spent on code linting and code generation, because we already had problems with them, and we spotted them through monitoring.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*REdGxDiJjDUKwH9JgI54nw.png" /><figcaption>Build Phases Duration chart</figcaption></figure><p>And we also have graphs of the build time of our projects on different CI machines. For example, this graph shows how long it takes to build our application for employers on each of the CI agents. And you can clearly see that builds on the M1 mac mini are about a third faster than on older intel macs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TrWq1woS-1qNMHF3MFXFyw.png" /></figure><p>But when we opened this graph before preparing this article, we were very surprised. It turns out that project build time has slowed down quite a bit lately, and we missed it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lsv7RGYx51_Lqs_O2APOFA.png" /></figure><p>It turned out we accidentally integrated an unnecessary feature — that caused a sudden jump in build time. After disabling them the time has stabilized. Graphs like this allow you to notice build time issues earlier.</p><p><strong>Let’s summarize</strong></p><p>Measure the build time. It’s a good idea to start doing this as early as possible before you make any changes to your project. There are many different tools for measuring build time today, you just need to choose the one that is right for you. And if you have already set up a collection of metrics, don’t forget to keep track of them, so as not to accidentally overlook major changes.</p><p><em>Sounds fun? Subscribe to our </em><a href="https://t.me/hh_tech_news"><em>news channel on telegram</em></a><em> and “</em><a href="https://www.youtube.com/channel/UCWztYdpQS3v9Gjno8bBZcNA"><em>HHella cool stories</em></a><em>” channel so you won’t miss new videos, articles, and other news. And you can ask our engineers any questions on any topic in the comments or in </em><a href="https://t.me/hh_tech"><em>hh developers’ telegram-chat</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56bbc15c9c8f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hh-ru/build-time-in-ios-56bbc15c9c8f">Build time in iOS</a> was originally published in <a href="https://medium.com/hh-ru">hh.ru</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Контроль над ресурсами. Настраиваем SwiftGen]]></title>
            <link>https://medium.com/hh-ru/%D0%BA%D0%BE%D0%BD%D1%82%D1%80%D0%BE%D0%BB%D1%8C-%D0%BD%D0%B0%D0%B4-%D1%80%D0%B5%D1%81%D1%83%D1%80%D1%81%D0%B0%D0%BC%D0%B8-%D0%BD%D0%B0%D1%81%D1%82%D1%80%D0%B0%D0%B8%D0%B2%D0%B0%D0%B5%D0%BC-swiftgen-81da624b326c?source=rss-a589e9862836------2</link>
            <guid isPermaLink="false">https://medium.com/p/81da624b326c</guid>
            <category><![CDATA[codegen]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[swiftgen]]></category>
            <dc:creator><![CDATA[Yura Privezentsev]]></dc:creator>
            <pubDate>Fri, 06 Dec 2019 10:34:47 GMT</pubDate>
            <atom:updated>2019-12-06T12:00:23.492Z</atom:updated>
            <content:encoded><![CDATA[<p>Наверное, в каждом большом iOS-проекте-долгожителе можно наткнуться на иконки, которые нигде не используются, или обращения к ключам локализации, которые уже давно не существуют. Чаще всего такие ситуации возникают из-за невнимательности, а лучшее лекарство от невнимательности — автоматизация.<br>В iOS-команде HeadHunter мы большое внимание уделяем автоматизации рутинных задач, с которыми может столкнуться разработчик. Этой статьей мы хотим начать цикл рассказов о тех инструментах и подходах, которые упрощают нашу повседневную работу.</p><p>Какое-то время назад нам удалось взять ресурсы приложения под контроль с помощью утилиты SwiftGen. О том, как ее настроить, как с ней жить и как эта утилита помогает переложить проверку актуальности ресурсов на плечи компилятора, и пойдет речь под в статье.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RqSHPgo2Cacm7STS.jpeg" /></figure><p>SwiftGen — это утилита, которая позволяет генерировать Swift-код для доступа к различным ресурсам Xcode-проекта, среди них:</p><ul><li>шрифты;</li><li>цвета;</li><li>сториборды;</li><li>строки локализации;</li><li>ассеты.</li></ul><p>Подобный код инициализации изображений или строк локализации мог писать каждый:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95b883132fb520fe8849574636219e43/href">https://medium.com/media/95b883132fb520fe8849574636219e43/href</a></iframe><p>Для обозначения названия изображения или ключа локализации мы используем строковые литералы. То, что написано между двойными кавычками, никак не валидируется компилятором или средой разработки (Xcode). В этом кроется следующий набор проблем:</p><ul><li>можно сделать опечатку;</li><li>можно забыть обновить использование в коде после редактирования или удаления ключа/изображения.</li></ul><p>Давайте посмотрим, как мы можем улучшить подобный код с помощью SwiftGen.</p><p>Для нашей команды была актуальна генерация только для строк и ассетов, про них и пойдет речь в статье. Генерация для остальных типов ресурсов аналогична и при желании легко осваивается самостоятельно.</p><h4>Внедрение в проект</h4><p>Для начала нужно установить SwiftGen. Мы выбрали его установку через CocoaPods как удобный способ распространения утилиты между всеми участниками команды. Но это можно сделать и другими способами, которые детально описаны в <a href="https://github.com/SwiftGen/SwiftGen/tree/5.3.0#installation">документации</a>. В нашем случае все, что нужно сделать, — это добавить в Podfile pod &#39;SwiftGen&#39;, после чего добавить новую фазу сборки (Build Phase), которая будет запускать SwiftGen перед началом сборки проекта.</p><pre>&quot;$PODS_ROOT&quot;/SwiftGen/bin/swiftgen</pre><p>Важно выполнять запуск SwiftGen перед запуском фазы Compile Sources, чтобы избежать ошибок при компиляции проекта.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/0*z4T0HmWsFI5v9gdZ.png" /></figure><p>Теперь можно приступить к адаптации SwiftGen под наш проект.</p><h4>Настройка SwiftGen</h4><p>Первым делом необходимо настроить шаблоны, по которым будет генерироваться код для доступа к ресурсам. Утилита уже содержит набор шаблонов для генерации кода, их все можно посмотреть на <a href="https://github.com/SwiftGen/SwiftGen/tree/5.3.0/templates">гитхабе</a> и, в принципе, они готовы к использованию. Шаблоны пишутся на языке <a href="https://github.com/stencilproject/Stencil">Stencil</a>, возможно, вы с ним знакомы, если пользовались <a href="https://github.com/krzysztofzablocki/Sourcery">Sourcery</a> или играли с <a href="https://github.com/IBM-Swift/Kitura">Kitura</a>. При желании каждый из шаблонов можно адаптировать под свой стиль кода.<br> Для примера возьмем шаблон, который генерирует enum для доступа к строкам локализации. Нам показалось, что в стандартном слишком много лишнего и его можно упростить. Упрощенный пример с поясняющими комментариями можно посмотреть <a href="https://github.com/hhru/SwiftGen-Example/blob/master/SwiftGen/Templates/LocalizableStrings.stencil">в демо проекте</a>.</p><p>Сам файл шаблона удобно сохранить в корне проекта, например в папке SwiftGen/Templates, чтобы этот шаблон был доступен всем, кто работает над проектом.<br> Утилита поддерживает настройку через YAML-файл swiftgen.yml, в котором можно указать пути до исходных файлов, шаблонов и дополнительные параметры. Создадим его в корне проекта в папке Swiftgen, в эту же папку позже сгруппируем и другие файлы, связанные со скриптом.<br> Для нашего проекта этот файл может выглядеть так:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abd60fde101b7d4e93ac927d96428edd/href">https://medium.com/media/abd60fde101b7d4e93ac927d96428edd/href</a></iframe><p>По сути, там указаны пути до файлов и шаблонов, а также дополнительные параметры, которые передаются в контекст шаблона.<br> Так как файл лежит не в корне проекта, нам нужно указать путь до него при запуске Swiftgen. Изменим наш скрипт запуска:</p><pre>&quot;$PODS_ROOT&quot;/SwiftGen/bin/swiftgen config run --config SwiftGen/swiftgen.yml</pre><p>Теперь наш проект можно собрать. После сборки в папке проекта по указанным в swiftgen.yml путям должны появиться два файла Localization.swift и Image.swift. Их нужно добавить в Xcode-проект. Пример кода, который был сгенерирован с помощью SwiftGen также можно найти в демо проекте: <a href="https://github.com/hhru/SwiftGen-Example/blob/master/SwiftGenExample/Localization.swift">Localization.swift</a> и <a href="https://github.com/hhru/SwiftGen-Example/blob/master/SwiftGenExample/Image.swift">Image.swift</a>.</p><p>Теперь можно заменить все использования строк локализации и инициализации изображений вида UIImage(named: &quot;&quot;) на то, что у нас сгенерировалось. Это упростит нам отслеживание изменений в ключах строк локализаций или их удаление. В любом из этих случаев проект просто не соберется, пока все ошибки, связанные с изменениями, не будут исправлены.</p><p>После изменений наш код выглядит так:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6aaee08516763b55d9b3209fed8d51a/href">https://medium.com/media/a6aaee08516763b55d9b3209fed8d51a/href</a></iframe><h4>Настройка проекта в Xcode</h4><p>Есть одна проблема с генерируемыми файлами: их можно изменить вручную по ошибке, а так как они перезаписываются с нуля при каждой компиляции, эти изменения могут быть утеряны. Чтобы этого избежать, можно блокировать файлы на запись после исполнения скрипта SwiftGen.</p><p>Этого можно добиться с помощью команды chmod. Перепишем нашу Build Phase с запуском SwiftGen следующим образом:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74706385831e6f42ac763e664370ada8/href">https://medium.com/media/74706385831e6f42ac763e664370ada8/href</a></iframe><p>Скрипт получается довольно простой. Перед запуском генерации, если файлы существуют, мы выдаем для них права на запись. После выполнения скрипта мы блокируем возможность изменения файлов.<br> Для удобства редактирования и проверки скрипта на ревью удобно вынести его в отдельный файл runswiftgen.sh. Итоговый вариант скрипта с небольшими модификациями можно посмотреть <a href="https://github.com/hhru/SwiftGen-Example/blob/master/SwiftGen/runswiftgen.sh">здесь</a>. Теперь наша Build Phase будет выглядеть следующим образом: на вход скрипту передаем путь до папки Pods:</p><pre>&quot;$SRCROOT&quot;/SwiftGen/runswiftgen.sh &quot;$PODS_ROOT&quot;</pre><p>Пересобираем проект, и теперь при попытке изменения генерируемого файла вручную появится предупреждение:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E2BXd3C2iDovHUKF.png" /></figure><p>Итак, папка со Swiftgen теперь содержит файл конфигурации, скрипт для блокирования файлов и запуска Swiftgen и папку с настроенными шаблонами. Удобно добавить ее в проект для дальнейшего редактирования при необходимости.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/0*DNF-AoisT9l8CHiP.png" /></figure><p>А так как файлы Localization.swift и Image.swift генерируются автоматически, их можно добавить в .gitignore, чтобы лишний раз не решать в них конфликты после git merge.</p><p>Отдельно хочется обратить внимание, на необходимость указывать Input/Output Files для билд фазы SwiftGen, если в вашем проекте используется Xcode New Build System (она является системой сборки по умолчанию с Xcode 10). В списке Input Files необходимо указать все файлы, на основе которых генерируется код. В нашем случае это сам скрипт, конфиг, шаблоны, файлы .strings и .xcassets:</p><pre>$(SRCROOT)/SwiftGen/runswiftgen.sh <br>$(SRCROOT)/SwiftGen/swiftgen.yml $(SRCROOT)/SwiftGen/Templates/ImageAssets.stencil $(SRCROOT)/SwiftGen/Templates/LocalizableStrings.stencil $(SRCROOT)/SwiftGenExample/en.lproj/Localizable.strings $(SRCROOT)/SwiftGenExample/Assets.xcassets</pre><p>В Output Files поместим файлы, в которых SwiftGen генерирует код:</p><pre>$(SRCROOT)/SwiftGenExample/Image.swift $(SRCROOT)/SwiftGenExample/Localization.swift</pre><p>Указание этих файлов необходимо чтобы система сборки могла решить нужно ли запускать скрипт, в зависимости от наличия или отсутствия изменений в файлах, и в какой момент сборки проекта этот скрипт должен быть выполнен.</p><h3>Итоги</h3><p>SwiftGen — хороший инструмент для защиты от нашей невнимательности при работе с ресурсами проекта. С его помощью у нас получилось автоматически генерировать код для доступа к ресурсам приложения и переложить часть работы по проверке актуальности ресурсов на плечи компилятора, а значит, немного упростить нашу работу. Помимо этого, мы настроили проект Xcode, чтобы дальнейшая работа с инструментом была более удобной.</p><p><strong>Плюсы:</strong></p><ol><li>Легче контролировать ресурсы проекта.</li><li>Уменьшается вероятность опечаток, появляется возможность пользоваться автоподстановкой.</li><li>Ошибки проверяются на этапе компиляции.</li></ol><p><strong>Минусы:</strong></p><ol><li>Нет поддержки Localizable.stringsdict.</li><li>Не учитываются ресурсы, которые не используются.</li></ol><p>Полностью пример можно посмотреть на <a href="https://github.com/hhru/SwiftGen-Example">гитхабе</a></p><p><em>Оригинал статьи был опубликован на: </em><a href="https://habr.com/ru/company/hh/blog/423381/"><em>https://habr.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81da624b326c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hh-ru/%D0%BA%D0%BE%D0%BD%D1%82%D1%80%D0%BE%D0%BB%D1%8C-%D0%BD%D0%B0%D0%B4-%D1%80%D0%B5%D1%81%D1%83%D1%80%D1%81%D0%B0%D0%BC%D0%B8-%D0%BD%D0%B0%D1%81%D1%82%D1%80%D0%B0%D0%B8%D0%B2%D0%B0%D0%B5%D0%BC-swiftgen-81da624b326c">Контроль над ресурсами. Настраиваем SwiftGen</a> was originally published in <a href="https://medium.com/hh-ru">hh.ru</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>