<?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 Bruno Rovea on Medium]]></title>
        <description><![CDATA[Stories by Bruno Rovea on Medium]]></description>
        <link>https://medium.com/@brunoroveas?source=rss-4fa77b56b2bb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*PyKDLgWftKzLEpHHKLcY7A.jpeg</url>
            <title>Stories by Bruno Rovea on Medium</title>
            <link>https://medium.com/@brunoroveas?source=rss-4fa77b56b2bb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:45:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@brunoroveas/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[The Readers-Writers Problem (Swift Edition)]]></title>
            <link>https://medium.com/swlh/the-readers-writers-problem-swift-edition-dcba94c3f02d?source=rss-4fa77b56b2bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcba94c3f02d</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Bruno Rovea]]></dc:creator>
            <pubDate>Fri, 10 Jul 2020 18:05:07 GMT</pubDate>
            <atom:updated>2020-07-11T21:10:28.705Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IBSZZIO46PG2zZ0voGaLYg.jpeg" /></figure><p>The readers-writers problem is a concurrency problem faced when a shared resource that is not thread-safe can be read and written by multiple threads at the same time. The problem happens when one thread is reading or writing and another thread writes at the same time. In contrast, when the resource is only being read by more than one thread the problem doesn&#39;t appear since the resource is up to date and it won&#39;t provide outdated/wrong data.</p><p>Personally, I studied the concepts in college and studied the implementation on iOS for tech interviews, but luckily (and probably also irresponsibly) never had to use it professionally. Why luckily? Well, because we write (thread) unsafe code all the time, but we normally don’t suffer from this problem because of the architecture and/or use case (or sometimes, just luck). If you doubt it, know that a simple mutable array is not thread safe and when it is used we’re susceptible to suffer from this problem 😱</p><p>And this data structure is exactly the reason I’m writing this.</p><p>One of these days a weird, and very intermittent bug (I had to initialize the app lots and lots of times to firstly see it, since I didn’t know the cause) appeared in a list component that was fed by a shared resource. The bug consisted of one random cell duplicating the image from another cell.</p><p>The first thought was the cell reusability, but this component was already handled for this case before, and after a quick check to the code it was discarded.</p><p>Since it was a &quot;dumb&quot; component only consuming data from the shared resource, it had to be something with it. The shared resource had a mutable array that was only modified (written) internally by different functions depending on some business rules, but was read by a few objects, which also observed the resource for changes, so they could update themselves with the new data. And one of these objects included the list component. The shared resource code looked something like this:</p><pre><strong>private(set)</strong> <strong>var</strong> items: [Item] = []</pre><pre><strong>func</strong> fetchItems() {<br>  service.fetchItems { newItems <strong>in<br>    guard</strong> items != <strong>self</strong>.items <strong>else</strong> { <strong>return</strong> }<br>    <strong>self</strong>.items = items<br>    notifyUpdatedItems()<br>  }<br>}</pre><pre><strong>func</strong> addItem(<strong>_</strong> item: Item) {<br>  service.addItem(item) { addedItem <strong>in<br>    self</strong>.items.append(addedItem)<br>    notifyAddedItem()<br>  }<br>}</pre><pre><strong>func</strong> removeItem(<strong>_</strong> item: Item) {<br>  service.removeItem(item) {<br>    <strong>self</strong>.items.remove(item)<br>    notifyRemovedItem()<br>  }<br>}</pre><p>As we can see, we have one function for fetching all items, one for adding and another one for removing an item from the service, always notifying the observers and mutating the local array in the shared resource, which works as the <a href="https://en.wikipedia.org/wiki/Single_source_of_truth">SSoT</a> and <a href="https://en.wikipedia.org/wiki/Single_point_of_failure">SPOF</a> <strong>for this information</strong> through the app lifecycle.</p><p>Debugging the resource through breakpoints and inspection never showed any discrepancy probably because of the asynchronicity to debug without passing instruction by instruction, what would take ages to catch the problem. Because of a recent business rule the functions were being called more often in the app initialization, which caused the shared object to update itself everytime it was called. The guard statement we see in the fetch was to avoid an unnecessary update and it was working, not causing any problems, at least that was what we thought. Since debugging without appealing to Instruments didn’t bring any light, before going for the “big guns” I tried the developer&#39;s best friend, the old print statement, looking at the url returned from the resource. It was firing in order, like expected, but then in a random new initialization the duplication happened. When I saw it the bell rang and I remembered the college classes. The readers-writers problem!</p><p><strong>Since the functions were being called by different threads almost at the same time, eventually one read would happen at the same time of a write, causing a data race</strong>, that would cause the wrong url being fetched from the resource.</p><p>Fortunately it’s very simple to solve it in Swift, since we have DispatchQueues, and can also have a barrier that works as a Semaphore for free when needed, which can control any tasks we want to run.</p><p>The DispatchQueue can be either serial or concurrent.</p><pre><strong>let</strong> serialQueue = DispatchQueue(label: &quot;serial.queue&quot;)<br><strong>let</strong> concurrentQueue = DispatchQueue(label: &quot;concurrent.queue&quot;, attributes: .concurrent)</pre><p>As they say, one of them executes tasks serially while the other, parallelly, which can bring much more performance. There&#39;s another important parameter that is the <em>qos</em>, we should set the correct one for our case. We can read more about each option <a href="https://developer.apple.com/documentation/dispatch/dispatchqos">here</a>.</p><p>We could use the serial queue, so just one write or one read is executed at time.</p><pre><strong>private</strong> <strong>var</strong> _items: [Item] = []<br><strong>private(set)</strong> <strong>var</strong> items: [Item] {<br>  <strong>get</strong> { serialQueue.sync { <strong>self</strong>._items } }<br>  <strong>set</strong> { serialQueue.async { <strong>self</strong>._items = newValue } }<br>}</pre><p>We need an auxiliar array because the API for this object provides an array of items to be accessed directly, that&#39;s why we have the <em>queue</em> on the <em>get</em>, but if our API provides the array through a function, we can use the array as private and embbed the <em>queue</em> call in the function. Since we use the <em>get</em>, we also need to use the <em>set</em>, but if we go with the other approach, we can also put the <em>queue</em> call in each function that writes in the array.</p><p>But since we said in the beginning that <strong>we only want to limit the writing</strong>, we can <strong>use</strong> <strong>the barrier flag that will transform the concurrent queue in a serial one for that explicit task</strong>, when using it, <strong>the queue will wait for all pending tasks to finish, so it can run this task</strong>. After implementing the concurrent DispatchQueue, the code looked like this.</p><pre><strong>private</strong> <strong>var</strong> _items: [Item] = []<br><strong>private(set)</strong> <strong>var</strong> items: [Item] {<br>  <strong>get</strong> { concurrentQueue.sync { <strong>self</strong>._items } }<br>  <strong>set</strong> { concurrentQueue.async(flags: .barrier) { <strong>self</strong>._items = newValue } }<br>}</pre><p>Neat, right?</p><p>And after that? Well, duplication no more!</p><p>Thanks for the reading and hope it can help you in the future!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcba94c3f02d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/the-readers-writers-problem-swift-edition-dcba94c3f02d">The Readers-Writers Problem (Swift Edition)</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creational Patterns in Swift]]></title>
            <link>https://medium.com/@brunoroveas/creational-patterns-in-swift-c8a0aee35279?source=rss-4fa77b56b2bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8a0aee35279</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[design-pattern-ios]]></category>
            <category><![CDATA[creational-patterns]]></category>
            <dc:creator><![CDATA[Bruno Rovea]]></dc:creator>
            <pubDate>Mon, 13 Apr 2020 18:47:40 GMT</pubDate>
            <atom:updated>2020-04-13T18:47:40.137Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oRBlxfmKv_ThQPx8UWq-WA.jpeg" /></figure><p>Design Patterns are as the name say, patterns to design and architect our code, they are descriptions or strategies to solve common problems that all developers face in every project on all programming languages.</p><p>When developing for iOS, Swift in this case, the problems and the patterns to solve them are the same, we just need to adjust the syntax for it, which will help we build a more stable, predictable and maintainable code. Sometimes we already use it without knowing it’s a pattern, on the bright side maybe that’s good that you figured it for yourself :)</p><p>In this article we’re going to take a look at the Creational Patterns and how we can use it to help we build our application.</p><p>Creational Patterns are strategies for creating/initializing an entity, component or even a whole module. The most common being the Builder, the Factory and the Prototype patterns, which will be the ones we’re going to look at.</p><p><strong>Mind that the rational behind them are descriptive, not prescriptive</strong>, it’s our work to choose how to implement it, so the chunks of code we’re going to look are just examples of how to use them.</p><p>The first one that we’re going to tackle is the Builder, which is useful when we <strong>still don’t have all the information we need to simple init an entity at one point of time, when we need different representations from the same entity and when we need to validate any business logic through the input data, working with a step-by-step construction</strong>. It’s also very useful for us to not store the data in different properties, sending all of them through each step, the Builder can have the <strong>responsibility</strong> to store them, that way we only need to handle the Builder instance.</p><p>As an example, let’s say we want to create an User model, that we need to know if it can vote in an election.</p><pre>class User {<br>   let name: String = &quot;&quot;<br>   let age: Int = 0<br>   let canVote: Bool = false<br>}</pre><p>One simple way to create this model would be to create an initializer and just instantiate it, but as we said before, let’s say we don’t have all the data together to create it and/or we don’t want to pollute our model with business logic. That way we could make use of an UserBuilder:</p><pre>class UserBuilder {<br>   private let minimumAgeToVote: Int<br>   private let user = User()</pre><pre>   init(minimumAgeToVote: Int = 18) {<br>      self.minimumAgeToVote = minimumAgeToVote<br>   }</pre><pre>   func setName(_ name: String) {<br>      self.user.name = name<br>   }</pre><pre>   func setAge(_ age: Int) {<br>      self.user.age = age<br>      self.user.canVote = age &gt;= self.minimumAgeToVote<br>   }</pre><pre>   func build() -&gt; User {<br>      //do something else<br>      return self.user<br>   }<br>}</pre><p>As we can see, now the UserBuilder has the responsibility to build the User model, validating the business rule and being capable of receiving the data input through time, without specific order, which is useful in a registration flow, where we could pass the User Builder reference to each screen.</p><pre>let userBuilder = UserBuilder()<br>userBuilder.setName(&quot;John Doe&quot;)<br>userBuilder.setAge(&quot;21&quot;)</pre><pre>let user = userBuilder.build()</pre><p>We could also boost the Builder pattern using the Fluent Builder, which relies in chaining the functions retuning <strong>Self</strong>.</p><pre>class UserFluentBuilder {<br>   private let minimumAgeToVote: Int<br>   private let user = User()</pre><pre>   init(minimumAgeToVote: Int = 18) {<br>      self.minimumAgeToVote = minimumAgeToVote<br>   }</pre><pre>   func setName(_ name: String) -&gt; Self {<br>      self.user.name = name<br>      <br>      return self<br>   }</pre><pre>   func setAge(_ age: Int) -&gt; Self {<br>      self.user.age = age<br>      self.user.canVote = age &gt;= self.minimumAgeToVote<br>      <br>      return self<br>   }</pre><pre>   func build() -&gt; User {<br>      //do something else<br>      return self.user<br>   }<br>}</pre><p>As we can see, the only difference is the return type in our sets functions. The usage would be as follow:</p><pre>let user = UserBuilder().setName(&quot;John Doe&quot;)<br>                        .setAge(21)<br>                        .build()</pre><p>The FluentBuilder pattern is extremely efficient when we need an <strong>easy-to-read DSL to build a complex object</strong>.</p><p>To summarize, passing the logic to the Builder instead of the model, helps us to separate the concerns for the code, the power to build different representations from the same entity while giving us the freedom to build the model without a predefined order.</p><p>The second pattern is the Factory, which <strong>can be used to build a single abstract entity, </strong>but I personally like to use it for building<strong> a whole scene or module</strong>, mainly when using <a href="https://medium.com/@brunoroveas/coordinators-b29329582cdb">Coordinators</a>, <strong>where the logic can be complex</strong>, depending on external factors to the unit being built, like business logic, A/B testing and any other logic. It&#39;s the Factory function, along with the subclasses involved, the responsible to choose which concrete implementation will be built, but IMHO it can also be used to deliver the concrete type directly. We may ask why not just using the init function? Well, if we are delivering an abstract type, we wouldn&#39;t know which concrete type to build without validating all the logic and if we look at the concrete type initialization we should take in consideration the Dependency Inversion Principle and the Separation of Concerns, so an entity shouldn’t create its dependencies, let alone have to do any logic to build dependency A or B. This concern should be delegated to another entity, this one being the Factory.</p><p>The Factory can be used many ways, as a separated entity or as a static function in the model being built, and return the abstract type as the literature says or the concrete type as I think it should work too. Below we will see a case where we want to build a User details Scene, composed by a ViewController which depends on a ViewModel class, which depends on an User model and a Service class, which depends on a Network class. It may look complex, but for any presentation pattern different of Apple&#39;s MVC, this is very common and kind of simple.</p><pre>class ViewController {<br>   private let viewModel: ViewModel<br>   <br>   private init(viewModel: ViewModel) {<br>      self.viewModel = viewModel<br>   }<br>}</pre><pre>// MARK: - Factory<br>extension ViewController {<br>   static func build(with user: User, network: NetworkProtocol) -&gt; ViewController {<br>      let service = Service(network: network)<br>      let viewModel = ViewModel(user: user, service: service)<br>      let viewController = ViewController(viewModel: viewModel)</pre><pre>return viewController<br>   }<br>}</pre><p>Usage:</p><pre>let viewController = ViewController.build(with: User(), network: Network())</pre><p>As we can see, now the Scene can only be built using the Factory function, which is responsible for instantiating all dependencies, the concern is separated, the code is cleaner and easier to create integration tests, since the Scene single point of creation is well defined.</p><p>If we went with this approach, but needed to store some data to use later, let&#39;s say our Network class, so we can just call an instance function instead of a type function, we would need to play with a Factory entity inside the ViewController and use a Singleton pattern to guarantee its unicity.</p><p>While still talking about Factories, it&#39;s also common to use one single Factory to build all Scenes from a coordinator, a module or even the whole app. The catch? The Factory should have all the dependencies, the data we talked before, injected, so we can just call the functions with the business data.</p><p>Taking a look at the previous example, but adding an A/B testing service, we could change it to</p><pre>class ViewControllerFactory {<br>   private let network: Network<br>   private let abTestingService: ABTestingService</pre><pre>   init(network: Network, abTestingService: ABTestingService) {<br>      self.network = network<br>      self.abTestingService = abTestingService<br>   }</pre><pre>   func buildViewController(with user: User) -&gt; ViewController {<br>      let service = Service(network: self.network)<br>      let viewModel: ViewModelProtocol</pre><pre>      if self.abTestingService.ruleA {<br>         viewModel = ViewModelA(user: user, service: service)<br>      } else {<br>         viewModel = ViewModelB(user: user, service: service)<br>      }</pre><pre>      let viewController = ViewController(viewModel: viewModel)</pre><pre>      return viewController<br>   }<br>}</pre><p>Don&#39;t forget that for this option we should hold the Factory instance somewhere where we build the Scenes, so if we&#39;re using the Coordinator pattern, it would be better for the each Coordinator instance to hold it.</p><p>Both ways are commonly used and can be used interchangeably. Also, Factories can be chained, so a Factory can call another Factory to build any dependency needed.</p><p>The last one is the Prototype. The Prototype is used when we want to <strong>fully or partially use a default implementation</strong> <strong>of an entity, hiding the complexity of its creation</strong>.</p><p>Adding my opinion to the literature, for a Prototype to better do its job, we would need to know beforehand what should be the &quot;default implementation&quot; for the entity, maybe using the most used configurations or any other logic we would like to use.</p><p>Be in mind that for the Prototype, we should be careful with reference types, which will require a deep-copy of our entity to be handled. To simplify we will work with Structs in this demonstration, which doesn’t suffer of the reference problem, at least for this example ;-)</p><p>To the example: Let’s say we have a Car model, which we can configure the number of doors, the drivetrain’s wheel drive, along with other properties.</p><pre>Struct Car {<br>   var numberOfDoors: Int = 4<br>   var wheelDrive: WheelDrive = .FWD<br>   ...other properties<br>}</pre><pre>extension Car {<br>   enum WheelDrive {<br>      case AWD // All-wheel drive<br>      case FWD // Front-wheel drive<br>      case RWD // Rear-wheel drive<br>   }<br>}</pre><p>If we declare our model like this and don&#39;t pass any other value in the initializer, we will be creating a prototype with the property <em>numberOfDoors</em> with a value of 4 and the <em>wheelDrive</em> property with a value of .FWD. So if we want to change any of the values we can just change the properties after creating the instance.</p><p>Now you may be thinking, it&#39;s just a model with default parameters and no semantic values… well, it is! The prototype behaviour in this example is hidden, that way we should have another approach. If we want to give a more semantic value for a prototype, I would suggest to have a static func/var called prototype/default, which returns the desired prototype, that way we don’t pollute our properties declaration with values that may be not semantic at first glance. We would have something like this</p><pre>struct Car {<br>   var numberOfDoors: Int<br>   var wheelDrive: WheelDrive<br>   ...<br>}</pre><pre>extension Car {<br>   //Using a static property<br>   static let prototype: Car = Car(numberOfDoors: 4, wheelDrive: .FWD, ...)</pre><pre>   //Using a static function   <br>   static func prototype() -&gt; Car {<br>      Car(numberOfDoors: 4, wheelDrive: .FWD, ...)<br>   }<br>}</pre><p>So to use it, we would just call</p><pre>var asProperty: Car = Car.prototype<br>var asFunction: Car = Car.prototype()</pre><p>I think if we use the prototype like this, we have a more semantic value for the chosen values in the initializer, but as said before, be careful to use a deep-copy when using a reference type.</p><p>So, as I stated in the beginning, most of us already use Creational Patterns, even if we don’t know the right naming for them, but if you didn’t know and never used anything like this, I hope it gives you some enlightenment on how to solve any problems you meet and to build a better project in the future.</p><p>Do you know other ways to implement the Patterns shown above or use any other Creational Pattern that would be interesting to talk about? Share with us :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8a0aee35279" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to get the keyboard height (and use it)]]></title>
            <link>https://medium.com/@brunoroveas/how-to-get-the-keyboard-height-and-use-it-ceb4155cf662?source=rss-4fa77b56b2bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/ceb4155cf662</guid>
            <category><![CDATA[keyboard]]></category>
            <category><![CDATA[objective-c]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Bruno Rovea]]></dc:creator>
            <pubDate>Sat, 02 Feb 2019 22:07:49 GMT</pubDate>
            <atom:updated>2019-02-02T22:07:49.803Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cS7HxsC0sPWWYWblnA8n3w.jpeg" /></figure><p>Sometimes we have a scene where the user should input some data and normally uses the keyboard to do so, but when the keyboard shows, part of the UI gets covered, messing the UX.</p><p>To solve it, you have some different approaches, but one of them is to update the ViewController constraints to fit all the UI elements in the screen, so you can still have the same UX.</p><p>So, how to get the keyboard height when it shows and even important, when it hides?</p><p>Well, you should add an observer in your ViewController for each of the keyboard notifications, like in the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ab08d9cc8071d7efb40b0b0f7686159/href">https://medium.com/media/2ab08d9cc8071d7efb40b0b0f7686159/href</a></iframe><p>Note that we add an observer for each of the keyboard notifications and send it to a function that will handle the notification and animate the constraints using the keyboard height. Observe in the keyboardWillHide function that we assumed that you have the constraints original values somewhere, because if we execute the same code that is inside the keyboardWillShow function it will return zero (You could also save the keyboard height and use it to animate the constraints to the original value).</p><p>The code is pretty ugly and chunky isn&#39;t it? Along with that, the animation is not smooth, because we don&#39;t know the keyboard animation parameters. How can we solve it?</p><p>We can build a function to handle the animation when both notifications are called and use the keyboard animation parameters to animate the constraints, making the animation goes really smooth.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9629e64aba16faa0b124ca8ae0efa904/href">https://medium.com/media/9629e64aba16faa0b124ca8ae0efa904/href</a></iframe><p>At the cost of an even more chunky code we solved the animation and the code duplication with the example above. Solved the code duplication… wait, did we?</p><p>Remember that this code is for just one ViewController, so you will need to copy and paste this code for all ViewControllers you need to animate. It would be something around 40 lines of code for <strong>each</strong> ViewController. That&#39;s a <em>PITA</em> right?</p><p>So, how can you <em>DRY</em>?</p><p>To <em>DRY</em>, I see two possible solutions, use a BaseViewController or use an UIViewController extension.</p><h4>BaseViewController</h4><p>If you have a BaseViewController that&#39;s really a <em>base</em> for all ViewControllers, you can use the last shown code and update to the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d92d915c5527e9f1daa26937d1056bc/href">https://medium.com/media/3d92d915c5527e9f1daa26937d1056bc/href</a></iframe><p>If you don&#39;t want some ViewControllers to observe when the keyboard shows, just create another function inside the BaseViewController and change the observers from the viewDidLoad function to the new one. Now you can call it whenever you need.</p><h4>UIViewController+Extension</h4><p>Well, if you are like me and don&#39;t like to use BaseViewControllers, and/or don&#39;t want to create one just for it, you can use an UIViewController extension. But, you may be asking yourself, if I use an extension, how can I override the function inside it? Well, there&#39;s a way. The code will look almost the same as in the BaseViewController. Take a look:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49e38f2ad260b830304adf91a8c4fd02/href">https://medium.com/media/49e38f2ad260b830304adf91a8c4fd02/href</a></iframe><p>We create a function to handle only the observers (it was inside the viewDidLoad function in our BaseViewController), so when you need it, just call it in the viewDidLoad function of any of your ViewControllers.</p><p>One of the main differences between a superclass and an extension in Swift is that you can&#39;t override a function from an extension, while you can when subclassing (When the class or the function is not final of course).</p><p>So if you have a Swift function inside an extension, you can&#39;t override it. To be able to override it, you need to create the function making it visible to Objective-C with the @objc notation. Take a look in the animateConstraints function in both BaseViewController and UIViewController extension to spot the difference when using each one.</p><p>Well, while Swift and Objective-C coexist I don&#39;t think it&#39;s really a bad practice to do this. What do you think?</p><p>I hope this was helpful for what you came searching for.</p><p>Any comments, errors, improvements? Feel free to point it!</p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ceb4155cf662" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coordinators]]></title>
            <link>https://medium.com/@brunoroveas/coordinators-b29329582cdb?source=rss-4fa77b56b2bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/b29329582cdb</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile]]></category>
            <dc:creator><![CDATA[Bruno Rovea]]></dc:creator>
            <pubDate>Tue, 29 Jan 2019 19:50:53 GMT</pubDate>
            <atom:updated>2019-02-02T22:02:26.902Z</atom:updated>
            <content:encoded><![CDATA[<p>How to route between the application&#39;s flows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*1DhjKiCT7GW1gQa4pnyySw.jpeg" /></figure><p>First of all I have to say that this article was inspired by many other articles that made me learn how to use Coordinators, along with the experience of using this pattern to route the applications I work with.</p><p>Routing is some of the basic functions you should do to build an app. The complexity starts low, but increase with time when you need new scenes, new flows and support new business logic. Along with that you try to make your app scalable using OO and SOLID concepts to make it readable, reusable, testable and maintainable.</p><p>So what should you use to route your app and help you accomplish it? Coordinators!</p><p>In this article I&#39;ll try not to deep dive in code, trying to show the minimum for you to understand and build it yourself.</p><h3>Coordinator?</h3><p>So… what&#39;s a Coordinator? Well, a Coordinator is… a <em>coordinator</em>. Its purpose is to coordinate where and how your app should navigate, to and from a scene, if it&#39;s in the same flow or starting a new flow, based on business logic. If you don&#39;t know what a flow is, it&#39;s a concept of telling the <em>USER</em> a <em>STORY, </em>let&#39;s say, the authentication flow, the profile flow, the payment flow, the statement flow and so on. A flow is composed by a collections of screens, which we&#39;ll refer as scenes.</p><p>Let&#39;s think for one moment when you want to move from one point to another in your city. You take your car, take the first right on the Avenue Splash Scene, take the second left on the Highway Home Scene, there you pass through some possible exits, but you want to enter the Profile Scene Street, where you have a toll that asks for something in exchange to let you in, that&#39;s exactly what you will build when using Coordinators (Well not exactly because it won&#39;t be a traffic system).</p><p>Remember that a flow can be either horizontal or vertical.<br><strong>Horizontal flow:</strong> When you <em>push</em> a ViewController using a NavigationController.<br><strong>Vertical flow</strong>: When you <em>present</em> a ViewController.<br><em>Note: Even when you present a NavigationController and start using push, it&#39;s still a vertical flow.</em></p><h3>Normally, how do we navigate between scenes and flows?</h3><p>Well, everyone has seen all kind of code to push or present a ViewController. From my experience, I have seen:</p><pre><strong>switch NavigationOptions {</strong><br>   <strong><em>case .Segue</em>:</strong> Probably the first mode everyone used when started developing for iOS. It has serious limitations when navigating and lots of flaws to control flows. It should always be avoided when possible. </pre><pre>   <strong><em>case .Directly:</em></strong> Normally after you learn the use of Segues limitations, you start using push and present directly from the ViewController. It too has limitations when navigating, but supports initializing a ViewController that is not in the Storyboard, which is nice. This option is OK when you have an application with just a handful  of scenes, because it&#39;s easy to lose yourself when routing.<br>   <br>   <strong><em>case .Router</em>:</strong> For the last years, at least to me, Routers earned its space, but normally people misuse them, because they don&#39;t control the flows inside the Routers and make the routing from the ViewControllers, sometimes from ViewModels, and believe it, even from Services classes. This option is also OK when you have an application with just a handful of scenes, but also can be very powerful if used correctly.<br><strong>}</strong></pre><p>But, what if you have more than a handful of scenes? What if you have more than a couple of flows? What if the business logic and the flows are always changing because your UX is experimenting some A/B tests, or the project&#39;s manager said so or well, because yes.</p><p>That would be a headache for the developer to keep changing the code and rearrange the transitions between scenes and flows.</p><h3>So, how and when should you use Coordinators?</h3><p>Which presentation architecture should you choose to use Coordinators? Well, for what I have seen, any architecture is compatible with Coordinators, but from my experience and the use cases I had, it goes really well with MVVM, showing a powerful and, at the same time, simple solution to almost any application.</p><p>There are lots of ways to use Coordinators, below I&#39;ll show how <strong>I</strong> use it and try my best to show other ways to use them.</p><p>Remember that you don&#39;t need a <em>bazooka to kill a fly</em>. If you have a simple app with a handful of scenes, not many business logic and it probably won&#39;t change so soon, feel free to use segues, navigate directly to the scenes or even use routers (properly), but remember to finish the article and consider the Coordinator pattern an option too :)</p><h3>Building the Coordinator</h3><p>So let&#39;s get started. First of all, all Coordinators should conform to the Coordinator protocol which consists of just one function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/362d0369c841d24e9e324eefdf28d475/href">https://medium.com/media/362d0369c841d24e9e324eefdf28d475/href</a></iframe><p>You will call this functions after you have initialized the Coordinator and the business logic is ready to start the new flow.</p><p>But you may ask, what else do I have to put in a Coordinator for it to start working properly? Well, for my use cases, I normally use from 2 to 5 scenes on each flow, but it could be from 1 to <em>n</em> scenes, so to present the first scene, it would look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c46b78253c813e88b4aee55355200ea4/href">https://medium.com/media/c46b78253c813e88b4aee55355200ea4/href</a></iframe><p>In the example above, which we&#39;ll refer as the <em>child</em> Coordinator, we have the presenter which should be the <em>parent</em> Coordinator&#39;s scene and the ViewController that will make the transition to the <em>child</em> Coordinator and start the new flow. Inside the start function we create the first ViewController from the <em>child</em> Coordinator flow, make the DI and present it.</p><p>Looks great and simple, right?</p><h3>Navigating to a new scene</h3><p>That&#39;s nice and all, but how can I navigate to the second scene based on a business logic? Probably you&#39;ll have an action to trigger it, let&#39;s say an @IBAction and make the navigation logic there.</p><p>When you use Coordinators along with MVVM, the ViewController shouldn&#39;t know how to navigate, it should just send the user actions to the ViewModel, so the ViewModel will know what to do with the actions, that&#39;s why we put the navigationDelegate in the ViewModel in the example above.</p><p>The ViewController code should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/858fe212f1d0ffeca65934c49ab78129/href">https://medium.com/media/858fe212f1d0ffeca65934c49ab78129/href</a></iframe><p>And the ViewModel code should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d945ec122be2c37ce50168bffc72a423/href">https://medium.com/media/d945ec122be2c37ce50168bffc72a423/href</a></iframe><p>Now we extend the functionality of our Coordinator to handle the navigation protocol:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b345c6da103a3711c63d6833257d68a0/href">https://medium.com/media/b345c6da103a3711c63d6833257d68a0/href</a></iframe><p>Note that the function onNavigate could contain any parameters you would like to send to the next ViewController, injecting it in the ViewModel through DI.</p><p>Nice, right?</p><h3>Extension Navigating</h3><p>If you noticed, there&#39;s a mistake in the example above, because we expected an UIViewController as the presenter and then called push in the onNavigate function without referencing the possible embedded navigationController. So, how do we solve this? It depends!</p><p>Let&#39;s say you have a flow which you want to continue with a new Coordinator, but you want your user to feel that it haven&#39;t changed and use push to transition into it. You can send the current UINavigationController as the new Coordinator presenter, and then change from present to push the FirstViewController in the start function.</p><p>Now let&#39;s think the other way around and you want your user to feel that he changed flows and present the next ViewController. As I stated before, you can inject a new UINavigationController (if the new flow has a horizontal navigation inside it) or create one inside the new Coordinator, which I prefer. Take a look in the code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/742497e940f4080d54a1f8df8d6f1704/href">https://medium.com/media/742497e940f4080d54a1f8df8d6f1704/href</a></iframe><p>Now instead of the presenter you can use the private navigationController to push new ViewControllers in the flow and use it to dismiss the flow too.</p><h3>Navigating to a new Coordinator (flow)</h3><p>Navigating inside a Coordinator is pretty easy, right? But what about navigating to another Coordinator? Well, it&#39;s easier!</p><p>Take a look at the code below, what do you think?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ea6ff739234dc00d620c79f0558912d/href">https://medium.com/media/0ea6ff739234dc00d620c79f0558912d/href</a></iframe><p>We just need to save the reference of the new Coordinator, inside an array of child Coordinators that is in the current Coordinator so it won&#39;t be able automatically deallocated by ARC. If you&#39;re asking yourself about how you are going to dealloc it, remember on the previous topic that we said about dismissing the flow?</p><h3>You said dismiss? How about finishing a flow?</h3><p>So far so good, but how can we tell that a child Coordinator finished its flow to the parent Coordinator? And what if it needs to delivery something to the parent Coordinator to make it update itself or do something else?</p><p>Well, you can use the delegate <strong>or</strong> the closure pattern protocols.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee2bf11478386d3be5b50d9a831520a7/href">https://medium.com/media/ee2bf11478386d3be5b50d9a831520a7/href</a></iframe><p>The delegate protocol needs to be implemented by the parent Coordinator, while the closure protocol needs to be implemented by the child Coordinator.</p><p>When finishing don&#39;t forget to dealloc the child Coordinator you just dismissed. Below is the example with the delegation pattern.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acc9c17fdf78cd763cbfdbec7b2d72bd/href">https://medium.com/media/acc9c17fdf78cd763cbfdbec7b2d72bd/href</a></iframe><p>Just remember that we choose to dismiss or pop a child Coordinator inside itself using the presenter or the private navigationController reference. I have seen some people that chooses to dismiss the child Coordinator from the parent Coordinator, and that is up to you.</p><h3>And what about the initial flow (aka AppDelegate flow)?</h3><p>Normally we create the ApplicationCoordinator, and use it in the AppDelegate. There you can make the initial flow when your app just finished launching, when received a push notification or even when it is started by a deep link.</p><p>So you may ask, what would be the presenter in that case? Well, there are cases where people create a NavigationController in the AppDelegate and cases where people send the UIWindow as the ApplicationCoordinator presenter. I prefer the latter.</p><p>An example of an AppDelegate would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a4c18ce3f5350c57a7ed527edd78e4d/href">https://medium.com/media/8a4c18ce3f5350c57a7ed527edd78e4d/href</a></iframe><p>It&#39;s important to have a reference for the Application Coordinator, so it won&#39;t be deallocated and you can easily execute another flow if you receive a push notification or a deep link, or any other business rule.</p><p>It&#39;s inside the ApplicationCoordinator where we normally change the flow when it&#39;s necessary to change the UIWindow&#39;s root view controller. If you don&#39;t know what the UIWindow&#39;s root view controller is, it&#39;s the main ViewController of the current UIWindow, the one you probably used in the AppDelegate. If it still doesn&#39;t make sense, I advise you to search for it, because it&#39;s very important for apps with more than one flow that need to change it based on a business rule.</p><h3>OK, I&#39;m already tired of Coordinators. Is there anything else?</h3><p>Actually there is:<br>1. Sometimes you need to handle the UINavigationController back button and gestures actions to trigger something or even dealloc a Coordinator which was pushed(I&#39;ll update the article with it in the future, but you can take a look at UINavigationControllerDelegate to try one of the possibilities) <br>2. You can use a Reactive approach where you could decrease or even eliminate the <em>delegation of hell</em> that it may build with so many business&#39; logic.<br>3. You could supercharge your Coordinators with Routers inside them for an even more powerful navigation framework!</p><p>We won&#39;t talk about it for now because I think we&#39;ve covered most cases you would need to support small to medium complexity applications.</p><p>Of course some applications may have some business logic, flows, or any other necessities that Coordinators may not work properly with, but I think there won&#39;t be many cases.</p><p>Just remember that when you have a specialized class to be responsible for a part/function of your application, like the navigation part, you are one step closer to build a clean architecture and make use of some <em>buzzwords</em>, like SOLID, DRY, SSoT, KISS and many other, that sometimes sounds irritating and we don&#39;t care much about, but are really important when building a readable, reusable, testable and maintainable app.</p><p>Now I should apologize because I said I wouldn&#39;t show much code, but while writing I thought it would be easier seeing it implemented than just explaining with my own words :)</p><p>Any questions, comments, errors, improvements? Feel free to point it.</p><p>Thanks for the reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b29329582cdb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>