<?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 Oscar Swanros on Medium]]></title>
        <description><![CDATA[Stories by Oscar Swanros on Medium]]></description>
        <link>https://medium.com/@swanros?source=rss-b063258390c8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OK4wpP3ihULgCKFXpgiYpg.jpeg</url>
            <title>Stories by Oscar Swanros on Medium</title>
            <link>https://medium.com/@swanros?source=rss-b063258390c8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 14:51:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@swanros/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[Los hábitos que me mantuvieron cuerdo en 2020]]></title>
            <link>https://swanros.medium.com/los-h%C3%A1bitos-que-me-mantuvieron-cuerdo-en-2020-a6d8d1e8f478?source=rss-b063258390c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6d8d1e8f478</guid>
            <category><![CDATA[2020]]></category>
            <category><![CDATA[propósitos-de-año-nuevo]]></category>
            <category><![CDATA[salud-mental]]></category>
            <category><![CDATA[hábitos]]></category>
            <dc:creator><![CDATA[Oscar Swanros]]></dc:creator>
            <pubDate>Thu, 31 Dec 2020 00:02:57 GMT</pubDate>
            <atom:updated>2020-12-31T00:02:57.497Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Este artículo se publicó </em><a href="https://oscarswanros.com/los-habitos-que-me-mantuvieron-cuerdo-en-2020/"><em>originalmente en OscarSwanros.com</em></a><em>, donde escribo sobre productividad, creación de hábitos, trabajo remoto, y más. Tengo un newsletter que sale todos los jueves. Te toma 3 minutos leerlo. </em><a href="https://oscarswanros.com/"><em>Suscríbete aquí</em></a><em>.</em></p><p>Mucho se ha hablado acerca de cómo 2020 fue el año que nadie quería ni se merecía, pero que tal vez todos necesitábamos. No expandiré más al respecto, pero sí diré que lo que me ayudó a sobrellevar estos últimos 12 meses fue un marco de trabajo de hábitos que me dediqué a crear para ayudarme a mí mismo.</p><p>2020 fue el año en el que la ansiedad por fin terminó de cocinarse y se manifestó en el escenario principal de mi vida. La primera vez que realmente sentí un ataque de ansiedad que me hizo sentir que no podía respirar, y que mi corazón se me estaba saliendo del pecho. Sudé frío.</p><p>No fue algo bonito de ver. Lo que sí fue, fue un llamado a la acción de que algo debía de cambiar.</p><h3>Por qué construir hábitos</h3><p>Cada quien ve en los hábitos el beneficio que quiere o que necesita. En mi caso, durante el último año me he enfocado en construir hábitos que me ayudaran a mantenerme conectado con mi realidad, y tranquilo.</p><p>Construir hábitos es algo que hacemos por nosotros mismos. Para hacernos la vida más fácil, y asegurarnos de que no estamos simplemente tropezándonos con nuestros propios deseos, y luchando contra nuestro entorno.</p><p>Bajo esa premisa, lo que busqué fue crear un entorno que me permitiera mantenerme en mi centro, fomentar mi salud mental, y mantenerme lo más cuerdo posible. A continuación te quiero compartir los 3 hábitos principales que desarrollé en 2020, y cómo me ayudaron.</p><h3>El hábito de recordar y comprender lo que aprendo día a día</h3><p>Uno de los retos más grandes que enfrenté en este año fue asegurarme de estar reteniendo la mayor cantidad de información posible de todo lo que estaba investigando o aprendiendo.</p><p>Como dije, durante el último año estuve batallando con una caso de ansiedad generalizada, casi rayando en depresión. Esto me llevó a consumir mucha literatura, libros, blogs, revistas, buscando respuestas a lo que me estaba pasando. Encontré muchas lecturas muy buenas, conocí a muchos autores bastante inspiradores. Estaba genuinamente disfrutando aprender cada vez más sobre lo que me pasaba y cómo podía salir del hoyo.</p><p>Pero tenía un problema. No estaba reteniendo mucha de la información que estaba consumiendo. Atrapado entre la ansiedad que estaba intentando resolver y el flujo constante de información al que estaba teniendo acceso, me había creado un problema nuevo. Demasiada información que, como dicen, entraba por un oído y salía por el otro. Durante una temporada, me pudiste haber preguntado qué había aprendido el día anterior sobre productividad o salud mental, y lo único que habrías recibido de mi parte sería una mirada en blanco.</p><p>Afortunadamente encontré <a href="https://readwise.io/">Readwise</a>. Readwise es un servicio que automáticamente agrega el contenido resaltado de diferentes fuentes, como Kindle, Medium, o cualquier cosa que yo guarde a través de su extensión de Chrome. Todos los días a las 6 AM me llega un correo electrónico con 5 ideas o citas aleatorias, seleccionadas de todo el contenido que haya sido sincronizado.</p><p>En Readwise tengo almacenadas muchas ideas de diferentes artículos, sitios de internet, y libros. Gracias a Readwise, pude crearme el hábito de reafirmar cosas que he leído con anterioridad, para que no solamente sean cosas que leí, sino cosas que aprendí.</p><p>Fue relativamente sencillo crear ese hábito porque la misma aplicación está diseñada para fomentarlo, llevando una cuenta de los días consecutivos que has revisado tu resumen diario. Actualmente estoy en mi racha más larga, habiendo revisado mis ideas destacadas por 73 días seguidos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*zBcj6j-TLodoOtTg.jpeg" /></figure><p>Esta herramienta también tiene un sistema para implementar Repetición Espaciada, que es una técnica de aprendizaje usada para incrementar gradualmente la cantidad de información realmente útil que podemos almacenar en nuestro cerebro. Esto ha sido realmente útil para recordar ideas y conceptos que son importantes para mí.</p><p>Debo de aceptar que al inicio fue retador construir este hábito. Como todos, hubo algunas situaciones en las que pensé simplemente dejarlo de lado. Pero después de varios meses haciendo esto todos los días, estoy más que feliz de reportar que Readwise se ha convertido en parte integral de mis días.</p><p>A finales de 2020, sé que las ideas que en algún momento leí y me parecieron interesantes, están a mi disposición todos los días, de manera automática. Esto se ha vuelto invaluable para mí.</p><h3>El hábito de expresarme de manera sana y controlada</h3><p>Una parte crucial de lidiar con la ansiedad, para mí, fue aprender a expresarme mejor, de manera sana y controlada. En terapia, descubrí que para que una expresión sea fructífera, no necesariamente debe de haber una persona recibiendo el mensaje. Lo que importa es sacar lo que quiero decir. Expresarme, y punto.</p><p>Así que comencé una práctica para fomentar mejores formas de expresión, siguiendo diferentes estrategias.</p><p><strong>Primero, las páginas matutinas</strong>, o <em>Morning Pages</em>. En algún momento del año me encontré con Julia Cameron, una autora aclamada por el New York Times, por su trabajo en la rama de la creatividad. Cuando la encontré fue a través de <a href="https://juliacameronlive.com/basic-tools/morning-pages/">este video, titulado “Morning Pages”</a>, donde explica el concepto.</p><p>Las páginas matutinas son simplemente eso. 3 páginas de contenido que se escriben a primera hora de la mañana, todas las mañanas. No necesitan tener una temática en particular, ni una estructura específica. Simplemente debes de escribir lo que está en tu mente, hasta llenar 3 páginas. ¿Tienes hambre? Escríbelo. ¿Se te olvidó comprar la despensa? Adelante. ¿Estás peleada con tu hermana? Seguro.</p><p>El objetivo de escribir las páginas matutinas no es tener algo que se pueda usar después, sino despejar tu mente de todo lo que puedas estar pensando. Así, cuando por fin llegue la creatividad que necesitas para hacer tu trabajo, ya no estarás preocupándote por todo lo que escribiste. Porque ya lo expresaste.</p><p>Eventualmente encontré 750words.com. Básicamente lo que hicieron fue tomar el concepto de las páginas matutinas, y convertirlo en una aplicación y una comunidad.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f1YsT3uaF0QjWZin.png" /></figure><p>Además de eso, 750words.com tiene un sistema de recompensas, al igual que Readwise, para fomentar que escribas diario. Vas ganando ciertas insignias conforme vayas completando rachas de diferentes números de días consecutivos. Además, analizan lo que escribes y te comparten algunos análisis interesantes sobre lo que escribiste. Por ejemplo, esto es un poco de lo que la aplicación pudo intuir de lo que escribí el <a href="https://750words.com/entries/share/9870987">15 de octubre</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IYqhMracQj9SKoQ-.png" /></figure><p>Intenté usarlo por unas cuantas semanas, pero no me atrapó. Afortunadamente ya tenía el hábito creado cuando la descubrí. Pero no dudo que su sistema de insignias y demás extras que ofrecen fomente que crees el hábito. Si te interesa explorar el concepto de páginas matutinas, 750words.com es una excelente apuesta.</p><p><strong>Segundo, hacer <em>check-in</em> conmigo mismo antes de hacerlo con el mundo externo.</strong> <a href="https://amzn.to/2L3nrK2">Aprendí este concepto de Matthew McConaughey</a>.</p><p>¿Por qué siempre espetamos que no tenemos tiempo para nosotros? Tal vez es porque estamos muy pendientes de qué está pasando con el resto del mundo. Siempre manteniéndonos al tanto de qué es lo que está sucediendo a miles de kilómetros. Naturalmente, cuando llega el momento de por fin dedicarnos tiempo personal de calidad, sentimos que nunca es suficiente.</p><p>Matthew propone lo contrario. Dedicarnos tiempo a nosotros mismos antes de pensar en el resto del mundo.</p><p>Yo hago algo <em>por mí</em> tan pronto me despierto, antes de hacer cualquier otra cosa. Y durante el tiempo que he mantenido este hábito, ha tomado diferentes formas y estructuras. Algunos días medio por 10 minutos. Otros días escribo mi sueño o pesadillas en mi diario de sueños. Otros días, usualmente los que me cuestan un poco más de trabajo, simplemente levanto y estiro cada una de mis extremidades tanto como puedo.</p><p>Lo que sea que me funcione ese día. No hay limitantes. Lo único que importa es que lo primero que hago todos los días al levantarme es dedicarme un tiempo para preguntarme cómo estoy, prepararme para el día. Y debo hacer esto antes de agarrar mi celular.</p><p>Este hábito tan simple me ha permitido mantenerme más presente, e iniciar el día en la nota correcta.</p><p><strong>Tercero, pero no menos importante, mantener un diario.</strong> Tan simple como suena, crear y mantener un diario ha sido una de las mejores cosas que he hecho por mí en toda mi vida.</p><p>La ansiedad funciona diferente en cada uno de nosotros. Para mí significa no recordar qué fue lo que hice durante el día que estuve lidiando con ella. Y tener un diario me ha ayudado a regresar en el tiempo y reconstruir las memorias. Memorias que a su vez me hacen calmarme, porque si bien durante el día no me sentí presente, a través del diario puedo saber que <em>estuve</em> presente. Porque escribí mi diario.</p><p>También he usado diferentes estrategias para mantener mi diario, lo cual es importante. Después de todo, <a href="https://oscarswanros.com/friccion">lo que no quiero es crear una fricción innecesaria </a>que no me permita llegar a mis metas. Así que algunos días uso papel y pluma. Otros días tomo notas digitales. Algunas ves simplemente me envío un correo electrónico a mi mismo, el cual veré a primera hora en la mañana.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WQ6H_R-8F91DtRoR.jpg" /></figure><p>La meta con llevar el diario, así como con las páginas matutinas, es simplemente expresar mis pensamientos para que no se echen a perder en mi cabeza, generando más ansiedad. Liberar mi mente.</p><p>La forma en como llevo mi diario es usando una metodología llamada “diario intersticial”, que es la práctica de agregar notas al diario múltiples veces durante el día, sin que necesariamente tenga una estructura definida. Es una combinación entre cosas qué hacer, revisiones de ánimo y pensamientos.</p><p>Agrego cosas a mi diario varias veces al día, y lo que agrego es únicamente lo que está en ese momento en mi mente. Aquí hay una captura de pantalla de cómo se ve una entrada de mi diario. Observa las anotaciones de la hora en la que hice la entrada:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dPQ2QGEfhYkm4Ewj.png" /></figure><p>Puedes notar que tengo secciones para cosas personales, relacionadas con mis objetivos, y con el trabajo. Eso es porque a mí me interesa llevar un registro de ellas por separado, pero de ninguna manera es un requerimiento. Simplemente a mí me funciona.</p><p><strong>Finalmente,</strong> no utilizo ninguna de las estrategias antes mencionadas de manera exclusiva. Las veo como herramientas a mi disposición para ser usadas cuando yo crea que son más convenientes.</p><p>Y eso es la clave con los hábitos. Cuando construyes buenos hábitos, también puedes usarlos conforme los vayas necesitando.</p><h3>El hábito de ejercitarme por mi cuenta</h3><p>He estado haciendo ejercicio de manera regular y en forma por 3 años ya. Comencé en enero de 2018 cuando al caminar sin playera por en frente de un espejo, no me gustó lo que vi. Desde ese momento, decidí hacer un cambio.</p><p>36 meses después, peso 40 kg menos, y me siento mejor que nunca. Pero el esfuerzo continúa.</p><p>Durante los primeros años de mi camino a recuperar mi salud física me forcé a ir al gimnasio. Tenía un entrenador, una rutina, y una práctica constante que me ayudaron a comenzar con mi régimen. Sin embargo, para finales del 2019, me sentía atorado. Ir al gimnasio ya no me gustaba; no me llenaba. Sí, hacía pesas, pero no estaba disfrutando mi tiempo ahí.</p><p>Quién iba a decir que unos cuantos meses después todos los gimnasios estarían cerrados gracias a la pandemia. Así que ahora, sí o sí, debía de encontrar una manera de poder ejercitarme por mi cuenta, sin dependencias externas.</p><p>Logré crear el hábito de ejercitarme por mi cuenta, sin equipo complicado.</p><p>En el pasado he compartido con algunos amigos que desde mi perspectiva y experiencia, hacer ejercicio es una oportunidad para darle un respiro a mi mente. El hecho de que puedo bajar de peso, verme mejor, y ganar mi autoestima al mismo tiempo, es simplemente un valor agregado. Doble ganancia.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/0*vKQBuUVp6ohH1g06.png" /></figure><p>Construir el hábito de entrenar por mi cuenta también me ayudó a combatir muchas de las excusas que me impedían trabajar en mis metas físicas. Ahora estoy acostumbrado a trabajar con lo que tengo a la mano, sin preocuparme sobre si el gimnasio está lleno, o cuánto tiempo me tomará llegar a él. Así que, independientemente de dónde esté, o con quién esté, hacer ejercicio se ha vuelto tan fácil como tomar mis tennis y correr por 40 minutos.</p><p>En los últimos meses comencé a brincar la cuerda, así que ahora tengo otra manera de despejar mi mente por unos 30 minutos, y al mismo tiempo quemar unas cuantas calorías.</p><h3>La regla de los dos días</h3><p>Procuro no confundir la acción que emana del hábito, con el objetivo que estoy intentando cumplir y para el que estoy creando el hábito en primer lugar.</p><ol><li>Usar Readwise no es lo importante, sino el recordar de manera regular las cosas que son importantes para mí.</li><li>Escribir 3 páginas, meditar o llevar un diario no es el objetivo final, sino ejercitar mi habilidad de expresarme de manera clara y controlada, para que mis pensamientos no se echen a perder en mi cabeza.</li><li>Lo que a mí me importa no es tener un mejor cuerpo, sino darle un descanso mi cabeza de vez en cuando. El hecho de que me vea mejor y me sienta más contento con el espejo es secundario.</li></ol><p>Y como dije antes, esos tres hábitos no están necesariamente atados a reglas específicas o duras. Pero sí tengo una única regla que me impongo para asegurarme de que los hábitos que realmente me importan se queden conmigo. <strong>La regla de los dos días.</strong> Es la única regla en mi vida que realmente procuro no romper, y me atrevería a atribuirle mis éxitos manteniendo estos hábitos.</p><p><strong>La regla de los dos días dice que no debo de dejar pasar más de dos días en los que no haga aquella cosa que sea importante para mí convertir en nu hábito.</strong></p><p>Ejemplo práctico: si ya hice ejercicio ayer y hoy, <em>podría no hacer ejercicio</em> mañana ni pasado, pero el día después de mañana <strong>tengo</strong> que ejercitarme.</p><p>Tan simple como eso. La belleza de esta regla es que, dentro de la premisa, existe un campo para descansar. Así evitamos caer en la monotonía, y fomentamos aún más la creación del hábito.</p><h3>Los hábitos para 2021</h3><p>El último año fue tan vertiginoso que ya no sé qué esperar. 2020 estuvo lleno de retos, pero también de muchos aprendizajes, y me siento afortunado de poder estar escribiendo esto hoy.</p><p>No me queda más que prepararme, porque ahora que ya tengo estos hábitos creados para poder mantenerme en mi centro, creo que el siguiente año se trata de hábitos que me ayuden a crecer.</p><p>Por lo pronto, el hábito que estoy fomentado, y gracias al cual estás leyendo esto, es escribir más seguido para una audiencia en internet.</p><p>Estoy emocionado por reportar en 12 meses qué fue lo que aprendí.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6d8d1e8f478" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is the open source culture hurting new developers?]]></title>
            <link>https://swanros.medium.com/is-the-open-source-culture-hurting-new-developers-92b7b28046e3?source=rss-b063258390c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/92b7b28046e3</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <dc:creator><![CDATA[Oscar Swanros]]></dc:creator>
            <pubDate>Tue, 20 Sep 2016 14:37:41 GMT</pubDate>
            <atom:updated>2016-09-20T16:57:54.062Z</atom:updated>
            <content:encoded><![CDATA[<p>That’s a bold question to ask. But I’ve been thinking about it.</p><p>As a member of the iOS developer community, I see people interested in learning how to create iOS apps almost every day.</p><p>I’m a member of various Facebook groups dedicated to share tips and tricks for iOS development, or just asking simple questions to the community. It hurts a little when I see someone new to this world asking, for instance, how to download an image from the network and set it to an UIImageView, and all the responses just tell them to “install this pod,” or “download this library.” You can translate that example to almost every common problem new developers face when first starting to <em>learn</em> iOS Development.</p><p>Why it hurts? Because these youngsters are never going to learn all the details behind doing what they can so easily accomplish with a `pod install`.</p><p>I often respond with “it’s not that hard, and you don’t really need all of Alamofire to do that.” And that’s true. To download an image from the network and assign it to a image view you, at most, need 30 lines of code.</p><p>The open source community makes it so easy to add code that a) maybe you don’t need, b) maybe you don’t fully understand, that I fear the new generations won’t really know how the system works, but will know really well how CocoaPods or Carthage works. (Remember left-pad?)</p><p>If you’re someone starting in this trade, I urge you to spend some time learning what the ecosystem you’re trying to start developing for is really like, it being iOS, Rails, the week’s popular JavaScript framework, whatever.</p><p>Spend some time learning what it’s really like inside the frameworks you’re going to be using for the next years. Learn their tricks. Hack them.</p><p>Don’t get me wrong: using third party code can be (and is) a really easy solution to get things done. But in my experience, the actual learning happens when I get in there and mess things up. Don’t be afraid to mess things up.</p><p>The next time you’re trying to figure out how to do something specific, try to come up with a solution, and only then, look at what everyone else is doing. Rinse, repeat. That’s how you get good at something, not just blindly using someone else’s code.</p><p>Look for mentors that don’t show you the easy way, but that guide you through the rough way.</p><p><em>This post was originally published at the author’s </em><a href="http://swanros.com/is-the-open-source-culture-hurting-new-developers/"><em>personal blog</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92b7b28046e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I deal with JSON in Swift]]></title>
            <link>https://medium.com/ingenier%C3%ADa-reserbus/how-i-deal-with-json-in-swift-f729e9d7caa7?source=rss-b063258390c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f729e9d7caa7</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Oscar Swanros]]></dc:creator>
            <pubDate>Thu, 11 Feb 2016 16:11:36 GMT</pubDate>
            <atom:updated>2016-02-11T17:41:59.756Z</atom:updated>
            <content:encoded><![CDATA[<p>It seems that the new hot thing these days is open sourcing your Swift JSON parsing library.</p><p><a href="https://github.com/lyft/mapper">Lyft</a>, <a href="https://www.bignerdranch.com/blog/introducing-freddy-an-open-source-framework-for-parsing-json-in-swift/">Big Nerd Ranch</a>, <a href="https://robots.thoughtbot.com/efficient-json-in-swift-with-functional-concepts-and-generics">Thoughtbot</a>, to name a few, have their own drop-in solutions for handling JSON with Swift available for you to integrate in your projects. Other libraries like <a href="https://github.com/SwiftyJSON/SwiftyJSON">SwiftyJSON</a> and <a href="https://github.com/owensd/json-swift">json-swift</a>, <a href="https://github.com/Hearst-DD/ObjectMapper">ObjectMapper</a> are there too. All of them are great. All of them get the job done.</p><p>This post is not a tutorial on how to use those libraries, but just a description of how <em>I</em> deal with JSON in my Swift apps.</p><h3>Disclaimer</h3><p>I’m pretty biased. Personally, I think that handling JSON in Swift, while challenging at first (specially if you’re new to the language), can be a really simple task.</p><p>Also, I don’t use any of the libraries that I mentioned earlier. My method might seem a lot more verbose (and it is), but bear with me.</p><p>If you just want to parse some JSON <strong>now</strong>, stop reading and use any of the libraries linked earlier (I’d go with <a href="https://github.com/SwiftyJSON/SwiftyJSON">SwiftyJSON</a> or <a href="https://www.bignerdranch.com/blog/introducing-freddy-an-open-source-framework-for-parsing-json-in-swift/">Freddy</a>, from BNR). If you want to <strong><em>learn</em></strong> how to handle JSON in Swift, read along.</p><h3>Groundwork</h3><p>How can you decode JSON in Swift with Cocoa natively?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acbe1b2330c760cf7b4b4d34b09afdec/href">https://medium.com/media/acbe1b2330c760cf7b4b4d34b09afdec/href</a></iframe><p>At this point, the constant json’s type is AnyObject. Typically, you’d cast json to a dictionary of some type (maybe an Array, depending on the API you’re trying to consume):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa04dc00899497fefc3aa272625309a0/href">https://medium.com/media/fa04dc00899497fefc3aa272625309a0/href</a></iframe><p>Its our job now to extract data from that dictionary, and make sure that we can build our Swift models in a type-safe manner.</p><p>Lets define what basic data types we can retrieve from a JSON structure:</p><ol><li>Ints</li><li>Floats</li><li>Strings</li><li>Bools</li></ol><blockquote>Note<em>: Nested objects and arrays are just arrangements of the basic data types.</em></blockquote><p>Taking chapter from <a href="http://chris.eidhof.nl/posts/json-parsing-in-swift.html">Chris Eidhof’s approach</a>, I defined the following helper functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ede0514afe3dde517d7b99757e71a1df/href">https://medium.com/media/ede0514afe3dde517d7b99757e71a1df/href</a></iframe><p>Briefly:</p><ul><li>The flatten(_:) function takes a double optional and removes one level of optional-<em>ness</em>.</li><li>The custom operator &gt;&gt;&gt;= takes an optional of type A to the left, and a function that takes an A as a parameter and returns an optional B to the right. Basically, it says “apply.”</li></ul><p>These next functions retrieve data from JSON structures in a type-safe manner, and they’re the building blocks for what I’m trying to do here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b90bd5c7af5574f1fc86f753297eda62/href">https://medium.com/media/b90bd5c7af5574f1fc86f753297eda62/href</a></iframe><p>If we had the following JSON structure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3abc9234ee0403dbfb054c9ab96f01fd/href">https://medium.com/media/3abc9234ee0403dbfb054c9ab96f01fd/href</a></iframe><p>To get the age property, then:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2fc8ea794ae2c9bff6ace81206aab51/href">https://medium.com/media/a2fc8ea794ae2c9bff6ace81206aab51/href</a></iframe><h3>The fun part</h3><p>I defined a single protocol JSONParselable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75e281f838ebd9155428b101aca54e68/href">https://medium.com/media/75e281f838ebd9155428b101aca54e68/href</a></iframe><p>My types that can be inflated from a JSON structure need to conform to this protocol. The implementation is rather simple.</p><p>Say I’m trying to consume an API with the following JSON response:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/795a0ec46d35d86e75f8b13837b76a60/href">https://medium.com/media/795a0ec46d35d86e75f8b13837b76a60/href</a></iframe><p>Working from the inside-out, these are the models that I’d define:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c9c48ed679ff38c510ea37a77adfa14/href">https://medium.com/media/8c9c48ed679ff38c510ea37a77adfa14/href</a></iframe><p>Now I have models that map directly to my API definition, including proper handling of values that may not be in the response at all. Now, on to implementing the JSONParselable protocol.</p><p>I’ll do one of the inner models first:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2a18d35be9a51575f540e91404d2250/href">https://medium.com/media/d2a18d35be9a51575f540e91404d2250/href</a></iframe><p>Then…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b36fb811a3c636b7ecf30486046f768/href">https://medium.com/media/4b36fb811a3c636b7ecf30486046f768/href</a></iframe><p>Attention:</p><ol><li>Notice how the protocol implementation is done in an extension for each type. This to emphasize the notion that the actual type does not care about how it is created, as long as it is valid.</li><li>Up until this point, I haven’t dealt with nested objects.</li></ol><p>Next, I need to parse the main Book object. Here’s how I do it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5330481a5f6a763d43a56807f67a3e6/href">https://medium.com/media/b5330481a5f6a763d43a56807f67a3e6/href</a></iframe><p>Dissecting the last code listing:</p><ul><li><strong>#1</strong>: Make sure that the required data is in the JSON dictionary, and extract it accordingly.</li><li><strong>#2</strong>: Extract the dictionaries for authors and reviews respectively.</li><li><strong>#3</strong>: Return a new instance of Book passing the <strong>required</strong> data first.</li><li><strong>#4</strong>: For authors and reviews, we .flatMap the array of dictionaries, and construct an array of only valid Authors and Reviews.</li></ul><p>The final implementation would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8c5a47a28d39d668e101fcbc9f991ba/href">https://medium.com/media/f8c5a47a28d39d668e101fcbc9f991ba/href</a></iframe><p>At this point (#1), I have a fully-packaged, type-safe, valid instance of Book, with nested models, even, not only a type-safe JSON type that I still have to extract data from. 🎉</p><h3>Why do it this way</h3><p>My method is (really) verbose, I know. But think about this few points before calling me crazy:</p><ul><li>The end result using is not a “type-safe-parsed JSON object,” as most of the libraries out there give you, but a fully type-safe, valid model instance.</li><li>While this may seem a lot of work, it lets you be more granular about how you inflate your models from data from a server.</li><li>My method, at least to me, makes it easier to translate API documentation to code.</li></ul><p>Other highlights:</p><ul><li><strong>No custom operators to deal with.</strong> Yes, the &gt;&gt;&gt;= operator was defined, but it is not required for the actual implementation of the JSON parsing (<a href="https://github.com/thoughtbot/Argo">Argo</a>, for instance, <em>requires</em> you to use custom operators to perform the actual parsing)</li><li><strong>Modularity.</strong> Dealing with nested objects kinda solves itself. If you make every nested model conform to JSONParselable, you can just send the original JSON blob to the outermost object, and you’re done.</li></ul><h3>Extra!</h3><p>Did you notice that Author has two properties that their name makes you think they’re URLs but are actually Strings?</p><p>Using my method, they can actually be NSURL objects!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35b66f42d8007874b9389029ed881201/href">https://medium.com/media/35b66f42d8007874b9389029ed881201/href</a></iframe><p>So, there’s that.</p><h3>Wrapping up</h3><p>As I said at the beginning of this post, the JSON parsing libraries that are out there are really popular (because they work), and they can help you get from point A to point B really quick (if that’s what you want).</p><p>My issue with those libraries is that they are too general-purpose for my taste. They are designed to work out of the box with any generic JSON response.</p><p>However, my issue is that my apps are not interacting with a generic API expecting generic JSON — they interact with a very specific API that outputs very specific JSON.</p><p>If my problem is really specific, why not solve it very specifically?</p><p>Have anything to add? Leave it in the comments section. You can reach me as <a href="http://twitter.com/Swanros">@Swanros on Twitter</a>.</p><p><em>Originally published at </em><a href="http://swanros.com/how-i-deal-with-json-in-swift/"><em>swanros.com</em></a><em> on February 11, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f729e9d7caa7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ingenier%C3%ADa-reserbus/how-i-deal-with-json-in-swift-f729e9d7caa7">How I deal with JSON in Swift</a> was originally published in <a href="https://medium.com/ingenier%C3%ADa-reserbus">Reserbus Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>