<?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 Gwenn Guihal on Medium]]></title>
        <description><![CDATA[Stories by Gwenn Guihal on Medium]]></description>
        <link>https://medium.com/@gwennguihal?source=rss-aae4165d399------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tAYZhsiPwlSTx41-iAsBsA.jpeg</url>
            <title>Stories by Gwenn Guihal on Medium</title>
            <link>https://medium.com/@gwennguihal?source=rss-aae4165d399------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 15:15:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gwennguihal/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[Resilient deserialization in swift]]></title>
            <link>https://medium.com/@gwennguihal/resilient-deserialization-in-swift-c1e69635c7b5?source=rss-aae4165d399------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1e69635c7b5</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[serialization]]></category>
            <category><![CDATA[codable]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Gwenn Guihal]]></dc:creator>
            <pubDate>Tue, 04 Feb 2020 20:26:44 GMT</pubDate>
            <atom:updated>2020-02-04T20:26:44.105Z</atom:updated>
            <content:encoded><![CDATA[<p>You probably send or receive data over the network in your apps. You probably use Encodable and Decodable protocols to do that job. You have probably already been confronted with parsing errors because your backend is not available to ensure the validity of the data. How to deal with that ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xb8SPjNwKt3AUnRm" /><figcaption>Photo by <a href="https://unsplash.com/@hvranic?utm_source=medium&amp;utm_medium=referral">Ivan Vranić</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Here is an example of a payload from a webservice that returns a list of train tickets (extracted from a <a href="https://swagger.io/">swagger</a>). Because the backend calls another backend that calls another backend, that calls…etc, the data is not safe and all properties are optional except pnr.</p><pre>tickets:<br>    [{<br>        pnr: String* // Passenger Name Record<br>        departureDate: Date?<br>        arrivalDate: Date?<br>    }]<br>}</pre><pre>? &gt; optional<br>* &gt; mandatory</pre><p>But <strong>a train ticket without departure and arrival dates is not possible</strong>, at all. ️If you use this model in your app, you have to deal with a lot of guard in your display or logic layers each time you use it.</p><pre>struct Response: Codable {<br>    let tickets: [Ticket]<br>}</pre><pre>struct Ticket: Codable {<br>    let pnr: String<br>    let departureDate: Date?<br>    let arrivalDate: Date?<br>}</pre><pre>func viewModelFunction(ticket: Response.Ticket) {<br>    guard let departureDate = ticket.departureDate,<br>        let arrivalDate = ticket.departureDate else {<br>        // handle error<br>        return<br>    }<br>    let dateFormatter = DateFormatter()<br>    let departureDateString = dateFormatter.string(from: departureDate)<br>    let arrivalDateString = dateFormatter.string(from: arrivalDate)<br>    // ...<br>}</pre><h3>A solution : Pattern matching</h3><p>Thanks to a few lines of code, we make some changes to have a list of ticket status instead of a tickets list. Pretty simple. We can keep the previous naming to limit changes in the whole project.</p><pre>struct Ticket: Codable {<br>    <br>    struct Body: Codable {<br>        let pnr: String // duplicated according your needs<br>        let departureDate: Date<br>        let arrivalDate: Date<br>    }<br>    <br>    enum Status {<br>        case corrupt(Error)<br>        case valid(Body)<br>    }<br>    <br>    let pnr: String<br>    let status: Status<br>}</pre><h4>Readability</h4><p>The big force of this implementation is its readability. A new developper coming on the project understands immediately which properties are mandatory to use properly a ticket.</p><pre>response.tickets.forEach {<br>    switch $0.status {<br>    case .valid(let ticket):<br>        // display ticket<br>    case .corrupt(let error):<br>        // display error, try to refresh later<br>    }<br>}</pre><pre>response.tickets.compactMap { ticket -&gt; Response.Ticket.Body? in<br>    guard case .valid(let body) = ticket.status else {<br>        return nil<br>    }<br>    return body<br>}.forEach { ... }</pre><h4>Maintainability</h4><p>Another advantage is maintainability. You can easily add a new case according your needs. For retrocompatibility with old versions for example.</p><pre>enum Status {<br>    case downgraded(DowngradedBody)<br>    case corrupt(Error)<br>    case valid(Body)<br>}</pre><h4>Remove Optional</h4><p>Last but not least, you don’t have to handle with optionals anymore. The data you use is safe, required properties are present, your code is simpler. 👍</p><pre>func viewModelFunction(ticket: Response.Ticket.Body) {<br>    let dateFormatter = DateFormatter()<br>    let departureDateString = dateFormatter.string(from: ticket.departureDate)<br>    let arrivalDateString = dateFormatter.string(from: ticket.arrivalDate)<br>    // ...<br>}</pre><h3>Encode / Decode</h3><p>The counterpart is the decoding part. You have to implement a custom init(from decoder: Decoder) function. Not really painful because there are only to fields to handle (pnr and status). The rest is managed by the Ticket.Body which doesn’t need a custom implementation 🎉.</p><pre>extension Response.Ticket {<br>    public init(from decoder: Decoder) throws {<br>                    <br>        let container = try decoder.container(keyedBy: CodingKeys.self)<br>        let pnr = try container.decode(String.self, forKey: .pnr)<br>        <br>        do {<br>            <strong>let body = try Ticket.Body(from: decoder)<br></strong>            self.init(pnr: pnr, status: .valid(body))<br>        } catch(let parsingError) {<br>            self.init(pnr: pnr, status: .corrupt(parsingError))<br>        }<br>    }</pre><pre>    enum CodingKeys: String, CodingKey {<br>        case status<br>        case pnr<br>    }<br>}</pre><h4>Non fatal errors</h4><p>Finally, you can add a non fatal errors reporter using your favorite crash reporter (Firebase, Fabric, …) in order to track backend errors that aren’t supposed to exist.</p><pre>// ...<br>do {<br>    let body = try Ticket.Body(from: decoder)<br>    self.init(pnr: pnr, status: .valid(body))<br>} catch(let parsingError) {<br>    self.init(pnr: pnr, status: .corrupt(parsingError))<br><strong>    ErrorReporter.recordError(pnr: pnr, error: parsingError)</strong><br>}<br>// ...</pre><p>I hope you enjoyed this article, feel free to follow me on <a href="https://twitter.com/gwennguihal">Twitter</a> and ask<strong> </strong>any question you have in mind !</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1e69635c7b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TableView Datasource with SwiftUI-style syntax]]></title>
            <link>https://medium.com/@gwennguihal/tableview-datasource-with-swiftui-style-syntax-1372b3a04687?source=rss-aae4165d399------2</link>
            <guid isPermaLink="false">https://medium.com/p/1372b3a04687</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[function-builder]]></category>
            <category><![CDATA[dsl]]></category>
            <category><![CDATA[uitableview]]></category>
            <dc:creator><![CDATA[Gwenn Guihal]]></dc:creator>
            <pubDate>Wed, 02 Oct 2019 16:28:56 GMT</pubDate>
            <atom:updated>2019-11-26T10:39:58.414Z</atom:updated>
            <content:encoded><![CDATA[<h3>UITableView Datasource with SwiftUI-style syntax</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kFl3SvahDJ_3o2D1" /><figcaption>Photo by <a href="https://unsplash.com/@messalaciulla?utm_source=medium&amp;utm_medium=referral">Messala Ciulla</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>SwiftUI seems to be great but unfortunately developers will be able to use it only if they target their app on ios13.<br>But SwiftUI is built on top of some new swift 5.1 features that can be used with previous iOS versions.<br>It’s the case of @functionBuilder(<a href="https://github.com/apple/swift-evolution/blob/9992cf3c11c2d5e0ea20bee98657d93902d5b174/proposals/XXXX-function-builders.md">Swift Evolution Proposal</a>).</p><p>Some people have already explained the power of @functionBuilder, I invite you to read them if you need more information:</p><ul><li><a href="https://www.swiftbysundell.com/articles/the-swift-51-features-that-power-swiftuis-api/">The Swift 5.1 features that power SwiftUI&#39;s API | Swift by Sundell</a></li><li><a href="https://medium.com/@carson.katri/create-your-first-function-builder-in-5-minutes-b4a717390671">Create Your First Function Builder in 5 Minutes</a></li><li><a href="https://github.com/carson-katri/awesome-function-builders">carson-katri/awesome-function-builders</a></li></ul><p>The more I like with <em>SwiftUI</em> is the readability of the UI implementation. And It’s possible thanks to @functionBuilder. <br>I have been working for a few years on a library called <em>Collor</em> which provides a data-driven datasource for UICollectionView and several other features (diffing, decoration view handling, …):</p><p><a href="https://github.com/voyages-sncf-technologies/Collor">voyages-sncf-technologies/Collor</a></p><p>A datasource of a collectionView build with <em>Collor</em> looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f815b49277f6f7ecb08559db572a09e/href">https://medium.com/media/3f815b49277f6f7ecb08559db572a09e/href</a></iframe><p>When I saw first examples made with SwiftUI, I thought, why not do it on <em>Collor</em> ? It’s pretty much the same idea: an UI declarative implementation (or a kind of DSL)!<br>Because it’s a lot of work, I preferred to start the experimentation with UITableView, much simpler.</p><p>At the end of this article, a datasource of an UITableView will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b388700dadeb64c8d89a51983c244078/href">https://medium.com/media/b388700dadeb64c8d89a51983c244078/href</a></iframe><p>For this result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*u3jHUKcK1gg-PkR8QngARg.png" /></figure><p>Comparing to <em>Collor</em>’s datasource, all notions of appends have been removed for better readability. We are close to the <em>swiftUI</em> syntax:</p><pre>List(landmarks) { landmark in<br>   HStack {<br>      Image(landmark.thumbnail)<br>      Text(landmark.name)<br>      Spacer()<br>      <br>      if landmark.isFavorite {<br>         Image(systemName: &quot;star.fill&quot;)<br>            .foregroundColor(.yellow)<br>      }<br>   }<br>}</pre><h3>How does it work ?</h3><p>There is a kind of magic behind @functionBuilder. What I understand is that each line into the closure is used as an argument of the function, here the initialiser. For example:</p><pre>Section {            <br> Spacer()<br> LabelCell( TitleAdapter(label: item.title) )<br>}</pre><p>To really really really summarise, the compiler transforms these lines into :</p><pre>Section(contents: [Spacer(), LabelCell(TitleAdapter(label: item.title))])</pre><p>To do that, it is using this @functionBuilder:</p><pre>@_functionBuilder<br>public struct ContentBuilder {<br> public static func buildBlock(_ contents: Content?...) -&gt; Content {<br>  return SomeThing<br> }<br>}</pre><h3>Everything is Content</h3><p>First let’s create a new protocol Content. Content may contain an array of Content:</p><pre>public protocol Content {<br>    var contents: [Content]? { get }<br>}<br>public extension Content {<br>    var contents: [Content]? {<br>        nil<br>    }<br>}</pre><p>Then create a concrete type of Content, a Container:</p><pre>public struct Container: Content {<br>    public var contents: [Content]?<br>    public init(contents: [Content] = []) {<br>        self.contents = contents<br>    }<br>}</pre><p>Once we have that, we can finally create our own @functionBuilder. According the parameter, we create a Container which contains one or several contents.</p><pre>@_functionBuilder<br>public struct ContentBuilder {<br>    <br>    // only one Content<br>    public static func buildBlock(_ content: Content) -&gt; Content {<br>        return Container(contents: [content] )<br>    }<br>    <br>    // an array of Content<br>    public static func buildBlock(_ contents: Content?...) -&gt; Content {<br>        return Container(contents: contents.compactMap { $0 } )<br>    }<br>}</pre><p>And use it in the Container struct:</p><pre>extension Container {<br>    public init(@ContentBuilder _ builder: () -&gt; Content) {<br>        self.init(contents: builder().contents ?? [])<br>    }<br>}</pre><p>Now, we are able to create some Container by using the @functionBuilder syntax:</p><pre>let container = Container {<br>    Container {<br>        Container()<br>    }<br>    Container {<br>        Container {<br>            Container()<br>            Container()<br>        }<br>    }<br>}</pre><p>Interesting, isn’t ?</p><h3>UITableView Datasource</h3><p>A tableView datasource is composed by sections which contain themselves cells.<br>Of course, Section and Cell implement the Content protocol:</p><pre>public struct Section: Content {<br>    var cells: [Int : Cell] // indexPath.row, Cell<br>}</pre><pre>public protocol Cell: class, Content {<br>    var identifier: String { get }<br>    func getAdapter() -&gt; Adapter<br>}</pre><p>Cell is a protocol because we prefer protocol-oriented programming than inheritance.<br>A Cell is a description of an UITableViewCell. As we are using Storyboard, only the identifier property is required to create or reuse a cell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RXqzIw_wrRAxX-_oEoeu1Q.png" /></figure><p>An <em>adapter</em> is a viewModel, its job is to convert some inputs in a human readable output, for example a date:</p><pre>protocol LabelAdapter: Adapter {<br>    var label: NSAttributedString { get }<br>}</pre><pre>struct DateAdapter: LabelAdapter {<br> let label: NSAttributedString<br> let dateFormatter = DateFormatter(..)</pre><pre>  init(date: Date) {<br>    label = dateFormatter.string(from: date).style(//...)<br>   }<br>}</pre><p>Finally, the DataSource class is just a container of sections that implements UITableViewDataSource protocol:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30bdc6f142cd5154b6c4ddd9b1882553/href">https://medium.com/media/30bdc6f142cd5154b6c4ddd9b1882553/href</a></iframe><p>We just have to create a convenience initalizer to use it with @functionBuilder:</p><pre>public extension DataSource {<br>    convenience init(<a href="http://twitter.com/ContentBuilder">@ContentBuilder</a> _ builder: () -&gt; Content) {<br>        self.init()<br>        var sections = [Section]()<br>        Self.invalidate(contents: [builder()], sections: &amp;sections)<br>        self.sections = sections<br>    }<br>}</pre><p>Because a content could contain some contents (Container), we use a recursive method to build sections of the datasource:</p><pre>private static func invalidate(contents: [Content], sections: inout [Section]) {<br>    contents.forEach { content in<br>        switch (content, content.contents) {<br>        case (let section as Section, _):<br>            sections.append(section)<br>        case (_, .some(let contents)):<br>            invalidate(contents: contents, sections: &amp;sections)<br>        default:<br>            break<br>        }<br>    }<br>}</pre><h3>Loop, Map, CompactMap</h3><p>I said before everything is Content. It’s even more true when we need a loop in our code. For example @functionBuilder doesn’t allow that:</p><pre>model.items.forEach { item in<br>    LabelCell(TitleAdapter(label: item.title))<br>}</pre><p>The compiler doesn’t understand this code because it just want you return Content and nothing else. So, we have to implement our own ForEach, Map or CompactMap.<br>These structs also implements the Content protocol. <br>The following code is pretty understandable. You give a collection and a closure that transforms the collection elements into Content(s) and that’s it!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4619c501822b48ecb64f85074d6c34c2/href">https://medium.com/media/4619c501822b48ecb64f85074d6c34c2/href</a></iframe><p>Which gives us:</p><pre>Map(model.items) { item -&gt; Content in<br>    LabelCell(TitleAdapter(label: item.title))<br>}</pre><h3>If let …</h3><p>if let is not allowed either. Like the object Map, we need to create an IfLet object that return or not a Content according the input.<br>As always, IfLet implements the protocol Content.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a05d2eb1d4e578d832df3a93b5d39eb8/href">https://medium.com/media/a05d2eb1d4e578d832df3a93b5d39eb8/href</a></iframe><p>To use it as such:</p><pre>IfLet(item.subTitle) { (subTitle) -&gt; Content in<br>    LabelCell(SubtitleAdapter(label: subTitle))<br>}</pre><h3>More functional syntax</h3><p>I was inspired by <em>RxSwift</em> to have a more functional and more swifty implementation:</p><p><strong>Map</strong>:</p><pre>model.items.ui.map { item in<br> // ...<br>}</pre><p><strong>IfLet</strong> (using the same idea of the Optional.map()):</p><pre>item.subTitle.ui.map {<br> // ...<br>}</pre><p>I don’t explain the code here, you can have a look a the <a href="https://github.com/gwennguihal/TableViewUI">github</a> project if you are curious.</p><h3>Conclusion</h3><p>I hope you enjoyed this article, it’s a bunch of ideas but it’s not ready to go in production. @functionBuilder is a little magical and not well documented yet. I’ve been groping a lot to have something that works. Furthermore, the compiler doesn’t help you, error message are often mistaken.</p><p>Sources are available on github:</p><p><a href="https://github.com/gwennguihal/TableViewUI">gwennguihal/TableViewUI</a></p><p>My next job is to add @functionBuilder feature on <a href="https://github.com/voyages-sncf-technologies/Collor"><em>Collor</em></a> in order to create a collectionViewDataSource like this:</p><pre>let dataSource = DataSource {</pre><pre>Section {<br>        LabelCell(...)<br>        ImageCell(...)<br>        Spacer()<br>        Decoration(.purple) {<br>            Space()<br>            DescriptionCell(...)<br>            Decoration(.form) {<br>                Space()<br>                TextFieldCell(...)<br>            }<br>        }<br>    }<br>}</pre><p>Thanks for reading, and let me know what you think on <a href="https://twitter.com/gwennguihal">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1372b3a04687" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create your own UICollectionView API]]></title>
            <link>https://medium.com/@gwennguihal/create-your-own-uicollectionview-api-d13aea5ae642?source=rss-aae4165d399------2</link>
            <guid isPermaLink="false">https://medium.com/p/d13aea5ae642</guid>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[uicollectionview]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[layout]]></category>
            <dc:creator><![CDATA[Gwenn Guihal]]></dc:creator>
            <pubDate>Tue, 05 Mar 2019 08:36:21 GMT</pubDate>
            <atom:updated>2019-11-26T10:39:45.577Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will create an external framework that will expose some cells, a background and horizontal line decorationViews and one vertical custom UICollectionViewFlowLayout that manages margins and paddings between cells.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_-TRd5gLoK4MCikxd7Eyvw.png" /><figcaption>The app and it’s debug view</figcaption></figure><h3>Why using UICollectionview ?</h3><p>According to your app, using UICollectionView to build your screens could save you a lot of time, mostly if your screens are data-oriented and contextual.<br>It’s easier to add a cell between two others than updating constraints to show or hide an UI element.</p><p>A powerful feature of UICollectionView is DecorationView. Without adding complexity on your cells, you can add backgrounds behind some of them and reuse them in the whole app.</p><p>Finally, UICollectionView allows to animate changes in your screens with just a few lines of code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lEYJPm_M_aAXYkb7sBKfAg.png" /><figcaption>oui.sncf — quote screens made with Collor</figcaption></figure><h3>Why an API ?</h3><p>Most of the time, app screens are designed with the same design: same buttons, same elements in many screens with just different contents but same layout.</p><p>The purpose to create an API is to use these elements in the simplest way. The main goal of an UICollectionView API is to spend less time on building screens and to spend more time to implement and test the logic, improve details and have a more maintainable code.</p><p>Another advantage is to provide an overall UI consistency in the app and to create screens as closely as possible to the mockups given by your(s) designer(s).</p><h3>Collor</h3><p>The API provided by Apple for implementing UICollectionView is indexPath-oriented. At oui.sncf, we created an over-layer, called <a href="https://github.com/voyages-sncf-technologies/Collor/">Collor</a>, to have a data-oriented implementation. The main goal of this library is to describe, in one file, the structure of your UICollectionView.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V6q1JpH5n4eWJv6IN-5Jag.png" /><figcaption>DataSource of RealTime sample app</figcaption></figure><p>Before continuing reading this article, you should take a look at these two articles:</p><ul><li><a href="https://medium.com/@_myrddin_/collor-a-mvvm-data-oriented-framework-for-uicollectionview-b55e73d81a59">Collor: a MVVM data-oriented framework for UICollectionView</a></li><li><a href="https://medium.com/@_myrddin_/uicollectionview-how-to-easily-deal-with-updates-8f37064de388">UICollectionView: How to easily deal with updates</a></li></ul><h3>Let’s go</h3><h4>1) Creating your own framework</h4><p>For optimising compilation time and minimising dependencies, the best way is to create a framework in your workspace. We name it <em>CollorAPI</em>. If you project to use this framework in others projects, I suggest you to create a private pod.</p><p>We don’t explain the process of creating a framework here, you can find a lot of tutorials if you need one:</p><p><a href="https://medium.com/@rayane.kurrimboccus/modularize-an-ios-application-919b30e41e3c">Modularize an iOS application</a></p><h4>2) An unique section descriptor</h4><p>Most of the time, an unique customisable section descriptor is sufficient for our need.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d08f3c93f8584b1019fd7104250c0cc4/href">https://medium.com/media/d08f3c93f8584b1019fd7104250c0cc4/href</a></iframe><p>The second class we create in our new framework is a subclass of CollectionData inside of which we add a method to instantiate the section descriptor created just before:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d49991d27cc24eb6c9577d8bb1c816dc/href">https://medium.com/media/d49991d27cc24eb6c9577d8bb1c816dc/href</a></iframe><p>Right now, we can add sections easily:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcee8ac7b0687fc75d8dfb0984f867f5/href">https://medium.com/media/bcee8ac7b0687fc75d8dfb0984f867f5/href</a></iframe><h4>3) The builder</h4><p>Next step it’s the creation of the builder! It’s the object that will expose methods in order to facilitate the life of your team. For now, the builder exposes two functions to add a custom descriptors and a LabelCell:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4213ab2cd333a6be90a0b0d5ff344e2/href">https://medium.com/media/b4213ab2cd333a6be90a0b0d5ff344e2/href</a></iframe><p>Instead of passing as parameter an array of cells in the closure used to build a section, we pass the builder, then we save the informations owned by the builder in the section descriptor. Pretty simple ;)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d01e72603c2b59145868083995278b7/href">https://medium.com/media/8d01e72603c2b59145868083995278b7/href</a></iframe><p>Ok, it’s cool, our API becomes useful: for each type of generic cell (which is used at least twice in the project), the builder exposes a method to create one easily and it indexes all of these. At<em> oui.sncf</em>, we created more than 50 reusable cells and it’s not over yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V_uUzgtvlHQaOqaNjzSRUw.png" /><figcaption>List of generic cells in oui.sncf app</figcaption></figure><h4>4) Vertical spaces</h4><p>Each generic cell must be designed edge-to-edge. Then margin and padding will be handle in the layout of the collectionView and with section insets. By applying this rule, it is easier to respect design screens without adding complexity in the cell or adding empty cells to fill in the gaps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YLsym5i8CS9Xo7vO2EMPFQ.png" /><figcaption>edge-to-edge cells</figcaption></figure><p>First, we implement this feature in the builder:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ddaff09f4a3b7e956178d89e37d7b44/href">https://medium.com/media/5ddaff09f4a3b7e956178d89e37d7b44/href</a></iframe><p>Each time we need to add spaces between two cells, we just call builder.add(verticalSpace: .huge). This sample is simplified: It’s impossible to add spaces more than once and to add space at the beginning of a section (before the first cell). You can do that later, according to your need.</p><p>Spaces are stored in a dictionary, this dictionary is passed to the section then used in our custom layout:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cad75f46aca2058c461adb933719fe7c/href">https://medium.com/media/cad75f46aca2058c461adb933719fe7c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a30db631f9ca54eb22086ff0e059180b/href">https://medium.com/media/a30db631f9ca54eb22086ff0e059180b/href</a></iframe><p>Each time there is a verticalSpace, the globalOffset is incremented then the next cell origin is offset by this value. The content size is also offset by this value. With this code, you can now add spaces between cells with an elegant way and without dirty tricks :) Don’t forget to set the the custom layout as layout of the collectionView.</p><h4>5) Decorations</h4><p>The goal of decorationViews is to add some graphic parts behind cells but without altering them. In <em>CollorAPI</em> a decoration is represented by a decorationBlock. A decoration view needs an origin and a size: the origin is defined with the origin of the the first cell and the size is computed by the right bottom corner of the last cell (in a vertical layout). To get these informations, the decoration stores some properties:</p><ul><li>the sectionDescriptor (for retrieving section index and some other informations)</li><li>startItemIndex and endItemIndex (for computing indexPaths and retrieves cell attributes in the layout)</li><li>type: the decorationView type</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5042966a2cc307fd55b28ef11a2aebaa/href">https://medium.com/media/5042966a2cc307fd55b28ef11a2aebaa/href</a></iframe><p>Now, we just have to add this feature on our builder with two new methods:</p><ul><li>startDecorationBlock(:): get the current index of the section and begins a decorationBlock.</li><li>endDecorationBlock(:): get the current index of the section and ends the decorationBlock.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/741e025fdb0548ea1ecac4880e3288ff/href">https://medium.com/media/741e025fdb0548ea1ecac4880e3288ff/href</a></iframe><p>VerticalCollectionViewLayout is updated to handle decorationBlocks:<br>We loop on all decorationBlocks then, according to the type, decorationViews are created using layoutAttributes of cells computed just before with verticalSpaces.<br>Each time you need a new kind of decorationView, you just have to add a new entry in the enum DecorationBlockType and update the layout to handle it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9432829f242a3f56ef9a56b27e029823/href">https://medium.com/media/9432829f242a3f56ef9a56b27e029823/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fjEsJEw2WrNcaDiz4l2sBQ.png" /><figcaption>.whiteBordered decorationView result</figcaption></figure><p>Finally, the collectionData looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f364710fc870cc20864eed2c22c1f91f/href">https://medium.com/media/f364710fc870cc20864eed2c22c1f91f/href</a></iframe><p>You can download sources of the sample on <a href="https://github.com/voyages-sncf-technologies/Collor/tree/SampleCollorAPI">github (SampleCollorAPI branch)</a>. In this example, there is another type of DecorationBlockType: .horizontalLine. As its name suggests, it enables to add horizontal line between cells. You are free to improve the code for even more flexibility.</p><h4>6) To go further</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ZybPY-j2s21pXJ761WnAQ.png" /></figure><p>At <em>oui.sncf</em>, there are 11 decoration types. They enable to add a ticket background or build a journey timeline. For the timeline we created a nested builder inside the section builder. By this way, roles are well separated and the API remains simple to use by other developers. Cells are are shifted to the right in the layout in order to reuse them instead of creating new ones with inside offset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21638897c0585ac9d1218ffe5c64a6bb/href">https://medium.com/media/21638897c0585ac9d1218ffe5c64a6bb/href</a></iframe><p>To resume, in this article we went through the bases of your future framework. <strong>It is now up to you to make it evolve according to your needs!</strong></p><p>Thanks for reading, and let me know what you think on <a href="https://twitter.com/gwennguihal">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d13aea5ae642" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Troisix — the hungry Ogre (media kit)]]></title>
            <link>https://medium.com/@gwennguihal/troisix-the-hungry-ogre-media-kit-62bdd8eef3de?source=rss-aae4165d399------2</link>
            <guid isPermaLink="false">https://medium.com/p/62bdd8eef3de</guid>
            <category><![CDATA[games]]></category>
            <category><![CDATA[indie-game]]></category>
            <category><![CDATA[touch-arcade]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[media-kit]]></category>
            <dc:creator><![CDATA[Gwenn Guihal]]></dc:creator>
            <pubDate>Wed, 05 Sep 2018 06:53:22 GMT</pubDate>
            <atom:updated>2018-12-04T08:48:38.295Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*mCUECUejhogkCCl_XW-Sdw.gif" /></figure><blockquote>Have you ever played <a href="https://boardgamegeek.com/boardgame/13328/chromino">Chromino</a> ? I did with my family and while I was playing, I got the idea to create Troisix. Three years later, I’m proud to release it and I hope you will have as much fun playing it as I had developing it.</blockquote><blockquote>Gwenn</blockquote><h3>What’s Troisix</h3><h4>Official Description</h4><p><em>Troisix</em> is a puzzle game for iPhone and iPad that might look simple at first but will quickly make your head spin. Inspired by domino and chromino board games, Troisix is ​​reinventing the whole concept and bringing complexity and fun to the next level.</p><p>The colors like to play peacefully together, stick together and squabble nicely.<br>But one day, their peace is interrupted by the arrival of the Hungry Ogre. It started to capture colors to eat them afterwards.<br>The color need you, a born leader to help them defeat this evildoer. They’re counting on you!<br>Complete each level one by one by judiciously placing the colors and avoiding the traps of the Ogre. That will be the key to success!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FB-vzCmfut_c%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DB-vzCmfut_c&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FB-vzCmfut_c%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f5fbceb9fffdb5ed0107afdff02e509/href">https://medium.com/media/7f5fbceb9fffdb5ed0107afdff02e509/href</a></iframe><h4>Arround the game</h4><p><em>Troisix</em> was originally an intention to develop a game quickly. We planned to create the game in 6 months. But in facts, the game will be published after more 3 years of development.</p><p>It is inspired by <a href="https://boardgamegeek.com/boardgame/13328/chromino">Chromino</a> game : a straight forward gameplay, perfect for mobile games.</p><p>Rectangles have been replaced by hexagones, the rules have been updated to play in single mode, then a little bit of fun and complexity was added by introducing the hungry ogre.<br><em>Troisix</em> is destined for a large audience. It’s a reflexion puzzle game where a round should be played in five minutes max.</p><p>We spent quite some time on developing the game elements, specifically the tiles and the Ogre in order to make them look alive. For that, of course there is a sound design work but if you notice, the tiles move on themselves and react to events by compressing or stretching depending of the context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*BCmEr4QE-Qcdq1FmulkBLw.gif" /></figure><p>The bad ogre is inspired by <a href="https://en.wikipedia.org/wiki/Venom_(Marvel_Comics_character)">Venom</a>: An organic shape with the ability of morphing and stretching.</p><h4>Gameplay</h4><p>The gameplay is relatively easy: for placing a tile on the board, each of its colors must match the colors of other tiles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*CurIZR9sIoToc9LaUOxIbA.gif" /></figure><p>The game’s purpose is to get rid of the hungry ogre but it will prevent you reaching your goal. Actually in some levels, it will appear and eat tiles. Theses eaten tiles, becoming colorless, prevent to place other tiles close to them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*TUwiaybe0K0W2em0O6B0mA.gif" /></figure><p>Fortunately, when you make a great play, you receive a white bonus which can be placed without restriction on the board.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*ftsTgQag8l8WZO0smMixNg.gif" /></figure><h4>About the game</h4><p>The first 4 levels are tutorials then the game becomes more complex the more you play. At the beginning, you start with 7 tiles to place then this number can go up to 50 and so increases the complexity.</p><p><em>Troisix</em> offers different gameplays that can be combined together :</p><ul><li><strong>Place them all</strong>: You have to place all tiles or a defined count of them.</li><li><strong>Release them</strong>: One or many colors are captured, release them by cleverly placing the tiles for creating a path to join them.</li><li><strong>Against the clock challenge</strong>: According the level, you have to finish it in a defined time.</li><li><strong>Attack of the Ogre</strong>: Repeatedly, the ogre attack in order to block you.</li></ul><p><em>Troisix</em> currently includes 48 levels with varied degree of difficulty built around combination of the above.</p><p>Quite some evolution separates the original concept from the finished product : some functionalities were added and then removed, some killer features emerged in our mind at night and had to be quickly implemented, some critical concepts were longer thought through to improve the gameplay before being implemented, … anyway, we really enjoyed developing <em>Troisix</em> and hope you will have at least as much pleasure in playing it.</p><h4>Publishing</h4><p><em>Troisix</em> is translated in English and French for the moment. Translations into Chinese, Japanese and German are in progress.</p><p>The game is compatible with iPhone and iPad but is developed to be cross platform. It may be released for Android in the next 6 months and for PC/Mac later.</p><p>We are planning to add more levels in few weeks.</p><h4>Launch Details</h4><ul><li><strong>Release date: </strong>Thursday September 20, 2018</li><li><strong>Price: </strong>$1.99</li><li><strong>iTunes Link: </strong><a href="https://itunes.apple.com/app/troisix/id1326749077">https://itunes.apple.com/app/troisix/id1326749077</a></li><li><strong>Website: </strong><a href="https://etxeagames.com/">https://etxeagames.com</a></li><li><strong>Languages: </strong>English, French, Chinese</li></ul><h3>1.1 update</h3><p><strong>Release date: </strong>Thursday December 13, 2018</p><h4>What’s new:</h4><ul><li>Chinese localization</li><li>A time ranking leaderboard has been added on each level with GameCenter for challenging players each other.</li><li>Haptic feedbacks were improved to give to the user pertinent feedbacks like telling him or her when a tile is compatible with an empty place or if he’s trying to do a forbidden action.</li><li>First levels were adjusted to make them easier and an indicator has been added to explain when the ogre will attack.</li><li>4 new levels added!</li><li>iPhone Xs/XsMax/Xr + new iPad pro compatibility</li></ul><h3>They are talking about it</h3><ul><li><a href="https://toucharcade.com/2018/09/25/troisix-review/">&#39;Troisix&#39; Review - Y&#39;Ogre&#39;na Love It</a></li><li><a href="https://toucharcade.com/2018/09/10/troisix-preview/">&#39;Troisix&#39; is a Colorful Puzzler with Charm. And an Ogre</a></li><li><a href="https://www.mac4ever.com/actu/136001_troisix-un-jeu-de-reflexion-made-in-france-inspire-du-chromino">Troisix, un jeu de réflexion &quot;made in France&quot; inspiré du Chromino</a></li><li><a href="https://kickmygeek.com/test-jeu/iphone-ipad/troisix">Troisix</a></li><li><a href="https://www.pocketgamer.com/articles/078771/troisix-review/">Troisix review - &quot;A colourful if slightly vague puzzler&quot;</a></li><li><a href="https://appadvice.com/app/troisix/1326749077">Troisix by Gwenn Guihal</a></li></ul><h3>Etxeagames</h3><p>Etxeagames is a french indie studio created in 2014 by Gwenn Guihal. Gwenn is an ios developper who has worked at <a href="https://www.oui.sncf/">Oui.sncf</a> for 3 years. He’s making game during his free time: half an hour on public transport in the morning and an hour or two from time to time in the evening.</p><p>Gwenn is 34 years old and was flash developer before becoming an ios developper. Merging these 2 skills, he started creating his first mobile game in 2014: <a href="https://itunes.apple.com/us/app/yessir/id771609442"><strong>YesSir</strong></a>, an artillery game which was featured as best new game in the US Store. One year later, it has been released for the Apple TV and again featured on many countries.</p><p>The 2d engine <a href="http://cocos2d-x.org/">Cocos2d-x</a> is used for making these games. Gwenn wrote an <a href="https://bit.ly/2jjuuNI">article</a> in 2014 for the cocos2d-x community which explains the process of porting YesSir for the Apple TV.</p><p>At <em>Exteagames</em>, we are trying to create beautiful games, with attention for detail and user experience.</p><h3>Media Kit Goodies — photos, videos and GIFs</h3><h4>DropBox</h4><p>You can find all of the media on Dropbox: <a href="https://www.dropbox.com/sh/008v15j1bnx5nm0/AACtUAJzgj6G15cjL-wnEYlGa?dl=0">https://www.dropbox.com/sh/008v15j1bnx5nm0/AACtUAJzgj6G15cjL-wnEYlGa?dl=0</a></p><h4>Promo video</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FB-vzCmfut_c%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DB-vzCmfut_c&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FB-vzCmfut_c%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f5fbceb9fffdb5ed0107afdff02e509/href">https://medium.com/media/7f5fbceb9fffdb5ed0107afdff02e509/href</a></iframe><h4>GamePlay video</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FeMUDCQ80qTQ%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DeMUDCQ80qTQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FeMUDCQ80qTQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b19eae0644171b356d3dd32561c1c7f5/href">https://medium.com/media/b19eae0644171b356d3dd32561c1c7f5/href</a></iframe><h4>App Store iPhone Screenshots</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LMZYeBmg90A9t8PwftU9eg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S1U3CEbI85yZJQ91zN1ovw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dP7w5R_DZLYQ5wzrGRGGcQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JWooT-0lCOvozwTjPjI9Jg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mH0smoRAwLd2-ud_q0GpKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cW36VtOuwevE5FVGgKgvaA.png" /><figcaption>5,5 po</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ze3Pj1O0hikiRZSAmA__YA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xMAKPgqMWF3esA2eN1CQ_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H2xHHHw3xpk05JV8o0w9Xw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lOhvZz3p6jWGFglxUBpz4Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DcIVqMGtqb8dBAsCcVtpEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qwd23sF8_gWXna692mooKg.png" /><figcaption>5,8 po</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sspLmvzwEZTMBqnT1xA6Jg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gzl2tPnelvLLBLdnHchErg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kCPQRt-iIbu5sZgxpqW7jg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YafmWiaQZCwobRH-OUZOMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RqoqQFHlMj1M0dlhs3ng5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2OW3CoAG-h60Th3kSV4yaQ.png" /><figcaption>12,9 po</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wD68rK1Vr19VhD9UJyN_KA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*j5PVSh92eNwNW8rzbN35Kg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e5AsA2myyZ5aeJgYw-Ff1w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62bdd8eef3de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UICollectionView: How to easily deal with updates]]></title>
            <link>https://medium.com/@gwennguihal/uicollectionview-how-to-easily-deal-with-updates-8f37064de388?source=rss-aae4165d399------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f37064de388</guid>
            <category><![CDATA[decorationviews]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[layout]]></category>
            <category><![CDATA[uicollectionview]]></category>
            <category><![CDATA[mvvm]]></category>
            <dc:creator><![CDATA[Gwenn Guihal]]></dc:creator>
            <pubDate>Fri, 24 Nov 2017 10:15:50 GMT</pubDate>
            <atom:updated>2019-11-26T10:39:31.157Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S6PnM8SwRWzA9bfofROYdw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/-GUyf8ZCTHM?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jessica Ruscello</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>When you are using CollectionViews or TableViews, the difficult part is when you need to add, remove, move some cells or update their content.</p><blockquote>Even more when you are using decoration views.</blockquote><h3>Introduction</h3><p>Look at these 2 arrays:</p><pre>let old= [&quot;A&quot;,&quot;B&quot;]<br>let new= [&quot;B&quot;,&quot;C&quot;]</pre><p>The differences between these arrays is very straight forward to compute:</p><pre>deleted :  [0] // index in the old array<br>moved :    [(from:1, to:0)]<br>inserted : [1] // index in the new array<br>reloaded : []</pre><p>To compute this diff, we use a <strong>key</strong> to compare the two arrays, which is the value in the array in this case. With key, we can compute <strong>moves</strong>, <strong>deletes</strong> and <strong>inserts</strong>.</p><ul><li>the key A was deleted of position 0</li><li>the key B moved from position 1 to position 0</li><li>the key C was inserted at position 1</li></ul><p>It’s become more complicated when we want to compute reloaded indices between two arrays. We also need a <strong>key</strong>, and a <strong>value. </strong>If the <strong>value</strong> changes, we need to reload the item.</p><pre>let old = [(key:&quot;A&quot;,value:0), (key:&quot;B&quot;,value:0)]<br>let new = [(key:&quot;C&quot;,value:0), (key:&quot;B&quot;,value:1)]</pre><p>The result of the diff:</p><pre>deleted :  [0] // key A deleted<br>moved :    []<br>inserted : [0] // key C inserted<br>reloaded : [1] // value of B has changed</pre><p>Perfect, we can now swap Int indices by IndexPath indices:</p><pre>let old = [<br>(key:&quot;A&quot;, value:0, index:(section:0, item:0), <br>(key:&quot;B&quot;, value:0, index:(section:0, item:1))<br>]<br>let new = [<br>(key:&quot;C&quot;, value:0, index:(section:0, item:0)), <br>(key:&quot;B&quot;, value:1, index:(section:0, item:1))<br>(key:&quot;D&quot;, value:0, index:(section:0, item:2))<br>]</pre><pre>// diffing<br>deleted :  [(section:0, item:0)] // key A deleted<br>moved :    []<br>inserted : [(section:0, item:0), (section:0, item:2)] // keys C &amp; D<br>reloaded : [(section:0, item:1)] // value of B has changed</pre><p>With that, we can easily compute diff between twos collectionView dataSources!</p><p>Let’s start with a little sample: a real time “tweeter” app built with a custom layout. Each 2 seconds, the app receives a new feed and updates its collectionView. Each “tweet” is represented by a section, a cell for the content, a cell for the number of retweets and a cell for the favorites count. Retweet and favorites cells are only displayed if their count is positive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*gzH_TuLbM1hdrv9vDd6CEQ.gif" /></figure><p>For building collectionView, I’m using <a href="https://github.com/voyages-sncf-technologies/Collor/"><em>Collor</em></a>, a micro architecture for simplifying collectionView implementation.</p><p><strong>More info in a previous article </strong><a href="https://medium.com/@_myrddin_/collor-a-mvvm-data-oriented-framework-for-uicollectionview-b55e73d81a59"><strong>here</strong></a><strong>. I recommend to read it before continuing reading.</strong></p><p>There is the collectionData of the collectionView, one readable file, which describes the collectionView, it’s the model of the collectionView:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af651d63144f0187e4699b583bc2b6bc/href">https://medium.com/media/af651d63144f0187e4699b583bc2b6bc/href</a></iframe><h3>Diffing</h3><p>We use the <em>Collor</em> diffing feature to compute differences between feeds. It’s a big feature because, as a developper, you no longer have to manually update the collectionview if your model changes. <em>Collor</em> does it for you.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a7af7cf3a9ffa0666c8bf4c28478a79/href">https://medium.com/media/3a7af7cf3a9ffa0666c8bf4c28478a79/href</a></iframe><p>Each time the app receives a new feed, the collectionData is updated with the new data then the diff between the old and the new collectionData is computed and <em>Collor</em> returns the removed, inserted and reloaded indexPaths (the struct result). The collectionView is also updated with “beautiful” animations which help the user to understand what’s happening in you app.</p><p>Even if collectionview update animations are not gorgeous, it’s better than a classic reloadData().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*Qtjtj2V4Wp4wxu_w_bFvsQ.gif" /><figcaption>Updates without custom layout</figcaption></figure><p>In <em>Collor</em>, to compute inserts and deletes, you just need to add a unique key to descriptors, represented by uid() method:</p><pre>// section<br>TweetSectionDescriptor().<strong>uid(tweet.id)</strong><br>// items<br>TweetDescriptor(adapter: TweetAdapter(tweet: tweet)).<strong>uid(&quot;text&quot;)</strong></pre><pre>TweetInfoDescriptor(adapter: RetweetAdapter(tweet: tweet)).<strong>uid(&quot;retweet&quot;)</strong></pre><pre>TweetInfoDescriptor(adapter: FavoriteAdapter(tweet: tweet)).<strong>uid(&quot;favorite&quot;)</strong></pre><p>But, for computing reloads, <em>Collor</em> needs more information, it needs to know the “value” of the descriptor. This value is the adapter. But in <em>Collor</em>, CollectionAdapter protocol is not conform to Equatable, for many reasons. So, if you want to compute reloads, you have to make yours adapters conform to Diffable. If you don’t, because for some good reasons, you can use the key as value, the cell will be also deleted then re-inserted:</p><pre>TweetDescriptor(adapter: TweetAdapter(tweet: tweet))<br>.<strong>uid(&quot;text_\(tweet.text)&quot;)</strong></pre><p>The animation of reload is different from delete/insert:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*Uysl9RvlJd4HUNXPlap4ag.gif" /><figcaption>Delete (fading) then insert (fading) — adapter no conform to Diffable</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*j3AFb4GebHeY38pyR9xQoA.gif" /><figcaption>Reload (just fading disappearing) — adapter conform to Diffable</figcaption></figure><p>In our example, we decided to compute reloads, so we make our adapters conform to Diffable by implementing the isEqual(to other: Diffable?) -&gt; Boolmethod:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f70a6ec7dee84b5d41eacc7ac88cdbe/href">https://medium.com/media/9f70a6ec7dee84b5d41eacc7ac88cdbe/href</a></iframe><p>During diffing calculation, <em>Collor</em> will test, when keys and index are equal, if value has changed or not. If yes, the item will be reloaded.</p><h3>Custom Layout</h3><p>If you are using decoration views in custom layouts, you already noticed coding that can be really redundant. Furthermore, you also have to handle collectionView updates and manually delete or insert decoration views.</p><p><em>Collor</em> may help you by using theDecorationViewHandler feature.</p><p>DecorationViewHandler allows you to:</p><ul><li>Register view class or xib</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e9c2da36d020d304d979982a8f8cb53/href">https://medium.com/media/8e9c2da36d020d304d979982a8f8cb53/href</a></iframe><ul><li>cache then return decoration UICollectionViewLayoutAttributes</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a316ec1aa1d4c11f68bd27c42eb417db/href">https://medium.com/media/a316ec1aa1d4c11f68bd27c42eb417db/href</a></iframe><ul><li>Return attributes in rect</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82219a03716ae891c72b5271b9eadd6c/href">https://medium.com/media/82219a03716ae891c72b5271b9eadd6c/href</a></iframe><ul><li>Manages collectionView updates ❤️</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e472ed187d76906d4cc762ad3b542e30/href">https://medium.com/media/e472ed187d76906d4cc762ad3b542e30/href</a></iframe><p>DecorationViewsHandler reduces the number of lines of code and errors and manage for you updates! According updateItems it determines what decoration views to delete or insert.</p><p>UICollectionView is reusing views for memory optimisations. That’s why animations may seem strange sometimes: instead of creating a new background view (what a human would do), UICollectionView reuses another and move it from it’s old position to the new. You can improve this behaviour by overriding these methods: <br>- initialLayoutAttributesForAppearingDecorationElement(ofKind:at:)<br>- finalLayoutAttributesForDisappearingDecorationElement(ofKind:at:)</p><h3>Conclusion</h3><p>By using <em>Collor</em> for building your collectionViews, you no longer need to manually implement updates, either at the cell level or at decoration view level. Instead of reloading the whole collectionView and losing the user, you are able to show to the user what changes are happening in your app!</p><p>Have a look at the <em>realtime</em> sample on <a href="https://github.com/voyages-sncf-technologies/Collor">github</a>.</p><p>Thanks for reading, and let me know what you think on <a href="https://twitter.com/gwennguihal">Twitter</a>.</p><p><a href="https://github.com/voyages-sncf-technologies/Collor/">voyages-sncf-technologies/Collor</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f37064de388" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Collor: a MVVM data-oriented framework for UICollectionView]]></title>
            <link>https://medium.com/@gwennguihal/collor-a-mvvm-data-oriented-framework-for-uicollectionview-b55e73d81a59?source=rss-aae4165d399------2</link>
            <guid isPermaLink="false">https://medium.com/p/b55e73d81a59</guid>
            <category><![CDATA[difference]]></category>
            <category><![CDATA[uicollectionview]]></category>
            <category><![CDATA[updates]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Gwenn Guihal]]></dc:creator>
            <pubDate>Tue, 29 Aug 2017 08:33:29 GMT</pubDate>
            <atom:updated>2019-11-26T10:39:17.111Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ssKyyYLzgL70auqB8p_MA.jpeg" /></figure><h3>The problem</h3><p>At oui.sncf, the main app for booking train tickets in France and Europe, our main job is to display what the server sends to us, most of views are also dynamic. Furthermore, the app is often updated with new features, even static views evolve constantly.</p><p>So, we decided to use UICollectionView! It’s powerful, dynamic and customisable.</p><p>But the Apple’s indexPath oriented implementation could become messy when there is a lot of different items, like in the Voyages-sncf.com app:<br>Code duplication, switch case, difficult to maintain, risks of indexPath errors during updates, …</p><h3>Solution</h3><p>We have built a framework for one year for simplifying and accelerating our development of theses UICollectionView screens. The main goal of this library is to have in one file, a readable dataSource which represents the collectionView content.</p><p>We called it <em>Collor</em>, <strong>Coll[</strong>ectionViewDescript]<strong>or</strong>.</p><p><a href="https://github.com/voyages-sncf-technologies/Collor">https://github.com/voyages-sncf-technologies/Collor</a></p><p><em>Collor</em> makes two things:</p><ul><li>First, it provides a scalable micro architecture based on MVVM to organise the code and to avoid duplications.</li><li>Then, it provides some features in order to remove a lot of code needed by collectionView implementation like cell registering among other things, and to easily update the collectionView: deletion, insertion, reloading, diffing, ….</li></ul><h3>Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*6WMRfIWR7PzG7Hcf2fS-gQ.png" /></figure><p>To describe the collectionView, a collectionData object, which inherits from CollectionData<strong><em> </em></strong>is used. It is divided in section and items.</p><p>The UICollectionView dataSource asks the the collectionData to know the number of sections, the number of items in a section and what cell to dequeue.</p><p>A collectionData object contains an array of SectionDescriptors: SectionDescriptor implements the protocol SectionDescribable and handles some section features like sectionInset, minimumInteritemSpacing and minimumLineSpacing using by Apple’s FlowLayout. SectionDescriptor contains also an array of CellDescriptors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f689f7954c17023f386abe63d1d29677/href">https://medium.com/media/f689f7954c17023f386abe63d1d29677/href</a></iframe><p>CellDescriptor is the object which describes the collectionViewCell. It implements the protocol CollectionCellDescribable<strong><em>.</em></strong> It contains an adapter which transforms the model in a readable data and which is used by the UICollectionViewCell to display the data. CellDescriptor also handles the size of the cell.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7253b585df73bf902169b11f4467d51/href">https://medium.com/media/a7253b585df73bf902169b11f4467d51/href</a></iframe><p>Example of TitleAdapter. An adapter is most of cases a struct, it doesn’t need inheritance and is lightweight.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ec64d279b62859ce44167a409113f77/href">https://medium.com/media/8ec64d279b62859ce44167a409113f77/href</a></iframe><p>Finally, CollectionViewCell implements the protocol CollectionCellAdaptable<strong><em> </em></strong>and does nothing but makes the link between the adapter and the IBOutlets. You could use <em>Collor</em> with our legacy code thanks to swift extension.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8ade12431f1d83f98d94505a232ab1d/href">https://medium.com/media/d8ade12431f1d83f98d94505a232ab1d/href</a></iframe><p>For summarising, to display one cell, 4 objects are needed:</p><ul><li>1 cellDescriptor</li><li>1 adapter</li><li>1 UICollectionViewCell (swift file + xib)</li></ul><p>You may think it’s hard work, each time you need to create a cell, you have to create 4 files ? No, most of cases, once a cell and its descriptor are created, only creating a new adapter is required if your cell is well designed. It’s the purpose of <em>Collor</em>: reuse a maximum of things.</p><p>Furthermore, <em>Collor</em> comes with Xcode some file templates, which help to create cells and theirs associated files (xib, view, adapter, descriptor), sections and even viewControllers, see <a href="https://github.com/voyages-sncf-technologies/Collor#xctemplates">here</a> how to install it.</p><h3>Reusability</h3><p>The goal of <em>Collor</em> is to limit the creation of cells by re-using existing code. For one type of cell, there should be a view, a descriptor and an adapter protocol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*untAJ0YskofVhskz8Q9iiA.png" /><figcaption>The same collectionViewCell used in different screens</figcaption></figure><p>For example, on the Voyages-sncf.com app, each time we need a simple label cell, we just create a new adapter which implements the protocol VSCollectionLabelAdapter and we reuse both the UICollectionViewCell and its descriptor created previously.</p><p>The adapter manages the style of the label ; the label fills the whole cell using Autolayout and its height is calculated using NSAttributedString.boundingRect()<strong>.</strong></p><p>Some code for explaining what we did:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/917f4f936f755e5eae6005fa0e03aa02/href">https://medium.com/media/917f4f936f755e5eae6005fa0e03aa02/href</a></iframe><h3>Scalability</h3><p><em>Collor</em> is scalable, by example, in some cases, the cell width, the cell height or both could be defined in the adapter, or even the cell identifier and the cell className.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*0jQBa77BIC0Y2li4FYJs3A.png" /><figcaption>Two cells, two adapters but one descriptor</figcaption></figure><p>Indeed, you may have a descriptor which handles similar cells with minimal changes: an image on the left or on the right. So there will be two cells, but one descriptor and a common adapter protocol.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1801f40752389ca7e1ce5fe454a53f15/href">https://medium.com/media/1801f40752389ca7e1ce5fe454a53f15/href</a></iframe><p>Finally, descriptors can carry the UI part of the collectionView by settings some parameters which will be used by decoration views in your custom collectionView layout.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9957017671cd9ac188bad00fbf233dbd/href">https://medium.com/media/9957017671cd9ac188bad00fbf233dbd/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*dSbvUowTxsHMbz8Y7lBONA.png" /><figcaption>Each section has a background view handled by the collectionView Layout</figcaption></figure><p><em>Collor</em> is a protocol oriented framework. Instead of adding a property in the section descriptor, it could implement a new protocol BackgroundDrawable by example, so it can be reused in other custom layouts…</p><pre>protocol BackgroundDrawable {<br>   var backgroundInset: UIEdgeInsets { get set }<br>}</pre><h3><strong>CollectionView Updates</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*RDUPirMEBZRRSwJ91srRKw.gif" /></figure><p>If you already had to implement an expand/collapse in a tableView or collectionView, <em>Collor</em> should interest you.</p><p>Indeed, <em>Collor</em> provides some methods to add, remove, reload sections or items easily. Working with IndexPath is no more needed, you just manipulate descriptor references and <em>Collor</em> does the job. After updating the collectionData, <em>Collor</em> gives you a <a href="https://voyages-sncf-technologies.github.io/Collor/Structs/UpdateCollectionResult.html">result object</a> you use to update the collectionView by calling UICollectionView.performBatchUpdates(_:completion:) or UICollectionView.performUpdates(with:completion:). The data and the view are also always synchronised with the collectionView.</p><pre>let result = myCollectionData.update { updater in<br>    updater.remove(cells: [cellDescriptor])<br>    updater.append(sections: [blueSection], after: lastSection!)<br>    // ...<br>}<br>collectionView.performUpdates(with: result)</pre><p>Each update in your collectionData must be enclosed in the closure given by CollectionData.update(_:)</p><p>Have a look at the <em>pantone</em> sample on <a href="https://github.com/voyages-sncf-technologies/Collor">github</a>.</p><h3>Diffing</h3><h4>Diff Data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*HLKefn7zE8jznLRfUStpQg.gif" /></figure><p>With <em>Collor</em>, it’s possible to compute the diff between two datas. <em>Collor</em> is using the amazing <a href="https://github.com/jflinter/Dwifft">Dwifft</a> library by <a href="https://medium.com/u/e3352702b830">Jack Flintermann</a> to do that. It’s very useful if your data contains conditional displays.</p><p>Compute differences between two data states with a few lines of code:</p><pre>myModel.someChanges()<br>yourCollectionData.update(model: myModel)<br>let result = yourCollectionData.update{ updater in<br>    updater.diff()<br>}<br>collectionView.performUpdates(with: result)</pre><p>For using this feature, each section and each item must have an unique identifier, a string value:</p><pre>let yellowSection = MainColorSectionDescriptor().uid(&quot;yellowSection&quot;)<br>let yellowTitle = TitleDescriptor(adapter: TitleAdapter(color: .yellow)).uid(&quot;yellowTitle&quot;)</pre><p>Cells in different section can have a same id, when computing diffs, cell uid is concatenated with its section uid. In the previous example, yellowTitle uid is yellowSection/yellowTitle.</p><p>Have a look at the <em>random</em> sample on <a href="https://github.com/voyages-sncf-technologies/Collor">github</a>.</p><h4>Diff Section</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*VzA7-w7OPziZ0_LxEqzVcw.gif" /></figure><p>You may just make some changes in a single section. By example an expand collapse. It’s pointless to compute diffing on the entire data.</p><p><em>Collor</em> provides a feature to just compute differences in some sections:</p><pre>sectionDescriptor.isExpanded = !sectionDescriptor.isExpanded<br>let result = collectionData.update{ updater in<br>    updater.diff(sections: [sectionDescriptor])<br>}<br>collectionView.performUpdates(with: result)</pre><p>It’s because of this feature that each section building is enclosing in a closure. <em>Collor</em> can also have the old and the new state of the sectionDescriptor cells array.</p><pre>let section = MySectionDescriptor().reloadSection { cells in<br>    cells.append(...)<br>}</pre><p>Have a look at the <em>weather</em> sample on <a href="https://github.com/voyages-sncf-technologies/Collor">github</a>.</p><p>Thanks for reading, and let me know what you think on <a href="https://twitter.com/gwennguihal">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b55e73d81a59" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>