<?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 Tyler Milner on Medium]]></title>
        <description><![CDATA[Stories by Tyler Milner on Medium]]></description>
        <link>https://medium.com/@tyler.milner?source=rss-6a77f6e4f041------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*upvewPdKICoOpwly.</url>
            <title>Stories by Tyler Milner on Medium</title>
            <link>https://medium.com/@tyler.milner?source=rss-6a77f6e4f041------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 00:42:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tyler.milner/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[Spatial Computing with Apple Vision Pro — The Final Frontier?]]></title>
            <link>https://medium.com/atlas/spatial-computing-with-apple-vision-pro-the-final-frontier-65592d7a1342?source=rss-6a77f6e4f041------2</link>
            <guid isPermaLink="false">https://medium.com/p/65592d7a1342</guid>
            <category><![CDATA[spatial-computing]]></category>
            <category><![CDATA[vr-headset]]></category>
            <category><![CDATA[apple-vision-pro]]></category>
            <category><![CDATA[virtual-reality]]></category>
            <category><![CDATA[visionos]]></category>
            <dc:creator><![CDATA[Tyler Milner]]></dc:creator>
            <pubDate>Mon, 28 Aug 2023 19:54:50 GMT</pubDate>
            <atom:updated>2023-08-28T19:54:50.955Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spatial Computing with Apple Vision Pro — The Final Frontier?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aOlIy5qQyAe1s91F2Nn12g.jpeg" /><figcaption>“VR headset spatial computing”, generated using <a href="https://stablediffusionweb.com/StableDiffusionXL">SDXL</a>.</figcaption></figure><p>It’s been a couple of months since Apple unveiled their new “Vision Pro” headset and its “visionOS” operating system. Now that the initial hype has died down and we’ve had a little while to digest and dive into some of the related WWDC 2023 session videos, what can we expect from this new product? Will this finally propel Alternate Reality (AR) experiences into the mainstream market and usher in a new area of “spatial computing”? Let’s review the device’s capabilities and what we might be able to expect after the device launches next year.</p><h3>What is Apple Vision Pro?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Acf0Znf7pGORbqwf5jrYgQ.png" /><figcaption>Apple Vision Pro side profile. Image credit: <a href="https://www.apple.com/apple-vision-pro/">Apple</a>.</figcaption></figure><p>Just in case you need a quick refresher, the Vision Pro is Apple’s first headset computing device. If you paid close attention during the <a href="https://developer.apple.com/videos/play/wwdc2023/101/">WWDC 2023 keynote</a>, you might notice that Apple never once mentioned the terms “Augmented Reality” (AR), “Virtual Reality” (VR), or “Mixed Reality” (MR). In addition to Apple’s obsessive need to brand any and everything, they likely avoided these terms to steer clear of any negative pre-existing associations people might have with those words based on their prior experiences with VR-related experiences. Instead, this is a new “spatial computing” device that promises to change the way we interact with computers…more on that in a bit.</p><p>Although primarily thought of as a display, the Vision Pro is actually a fully independent computing device that runs a new operating system — visionOS. This joins Apple’s existing OS lineup of iOS, iPadOS, tvOS, watchOS, and macOS. While developers can technically start building apps in a simulator and even apply to be loaned a Vision Pro development kit from Apple, the product won’t be released to the public until early 2024 at a $3499 starting price. Of course, this is Apple we’re talking about, and you’ll be lucky if you only pay that much. Realistically, I would expect most people will be shelling out well over $4000 after adding things like Apple Care, lens inserts for glasses users, and other accessories. This is by no means a cheap piece of computing equipment, but the hardware and software capabilities that Apple is promising are still very exciting nonetheless.</p><h4>Hardware</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*juCnNrv6w27I7YMVJYMBrA.png" /><figcaption>Apple Vision Pro eye tracking hardware. Image credit: <a href="https://www.apple.com/apple-vision-pro/">Apple</a>.</figcaption></figure><p>Hardware-wise, this headset has cutting-edge VR specs, which easily make it the most powerful and capable VR headset to date. Real world and virtual content is combined and projected onto each of your eyeballs by a pair of postage stamp-sized screens that each run at a resolution higher than your 4K TV. It’s using the new M2 processor — the same one that’s in the latest iPads and MacBooks. Also included is a new “R1” processor, which is dedicated exclusively to processing real-time sensor data. Together, these two chips should provide an experience with extremely minimal latency, which is critical to avoid people becoming sick while using the device.</p><p>Sensor-wise, this thing is also loaded. In addition to all of the standard smartphone sensors you would expect, such as a microphone, accelerometer, gyroscope, and LiDAR, there are also something like 14 cameras built-in to the device. You’ve got main cameras, downward cameras, side cameras, and even inward-facing True Depth IR cameras for eye tracking. At this point, I feel like Apple might as well have added a couple of cameras on the back to give you some sort of cool (but surely nauseating) 360° vision.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*aPV_x-KgZOPwBXpNzuj-Dg.png" /><figcaption>Apple Vision Pro external display showing user’s eyes beneath the device. Image credit: <a href="https://www.apple.com/apple-vision-pro/">Apple</a>.</figcaption></figure><p>There is also an external display, which is interesting since it’s not something we’ve seen on VR headsets and actually aims to perform a couple of useful functions. First, it allows others to see your eyes when you’re interacting with them while wearing the headset. Since the device isn’t actually see-through, Apple is using the internal cameras to project a virtual representation of your actual eyes onto the external screen. The internal eye tracking also enables <a href="https://en.wikipedia.org/wiki/Foveated_rendering">foveated rendering</a>, which ensures that the center area of your vision is rendered in the highest detail, similar to how our eyes work in real life. Second, the external display also allows others to see when you’re “fully immersed” in a VR experience. In other words, when you’re busy watching a movie on your own personal virtual 100-foot-wide movie screen or are doing some other immersive task like gaming, people can see that you likely don’t want to be bothered.</p><p>In addition to enabling highly detailed and immersive VR and AR experiences, all of the processing power and plethora of sensors enable you to interact with the device without any external hardware. No need for clunky VR controllers or base stations setup on the walls behind you. If desired, you can still connect external input devices like game controllers and keyboards, but it’s not a requirement to use the device.</p><h4>Software</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*Q5OfZS8SVGXsXVakG7J5WA.png" /><figcaption>Apple Vision Pro immersion levels. Image credit: <a href="https://developer.apple.com/visionos/planning/">Apple</a>.</figcaption></figure><p>On the software side of things, visionOS, the new operating system tailored for the Vision Pro, aims to integrate seamlessly into Apple’s current application and developer ecosystem. Out-of-the-box support for existing iPhone and iPad apps is available, allowing them to be run in a virtual window in front of you. No doubt, the recent work Apple did to allow iPhone and iPad apps to run on macOS via technologies like Mac Catalyst and Apple Silicon is being reused for this use case. Current Apple app developers also get a head start since creating visionOS apps builds upon familiar foundational technologies such as SwiftUI, ARKit, RealityKit, and several other frameworks that have been available for years. Beyond the specifics of how to integrate the AR/VR aspects of a visionOS app, there shouldn’t be many new frameworks or development techniques that developers need to learn.</p><p>With the Vision Pro having 14 cameras and tons of sensors looking around your space constantly while you’re using it, it’s nice to hear that Apple has taken privacy seriously with regard to what data apps can access. For instance, apps need to request access to raw sensor data via a standard system permission prompt, which users are already familiar with for other privacy-sensitive features like location and ad tracking. Only once permission is granted will apps be able to unlock advanced capabilities like scene understanding or high-resolution skeletal hand tracking.</p><p>One other welcome privacy feature provided by the OS is the disability of apps to track precisely where you’re looking. Although there is eye tracking inside the Vision Pro headset, the data about where a user is looking isn’t made directly available to apps. Instead, apps only receive touch events whenever you virtually “click” on something using the new pinch gesture. This is a very welcome feature since I’m sure advertisers would love to know exactly how long you looked at an ad or piece of content so that they can harvest even more of your information.</p><p>A brand new authentication mechanism is new to the Vision Pro as well. For a while now, we’ve had Touch ID and Face ID biometric capabilities integrated into several of Apple’s products, allowing users to quickly unlock their device via fingerprint or face, respectively. The Vision Pro will be outfitted with a new biometric solution called Optic ID. Almost as if straight out of a science fiction movie, the capability to authenticate via you eyes is finally a reality.</p><p>Lastly, one interesting aspect of the software and apps is the user-controllable immersion level. A digital crown, similar to the one on Apple Watch, allows users to control how “immersed” they are in the virtual space. Turn the dial all the way down to use the device in a “passthrough” mode where you can interact with 3D elements and apps in front of you, while staying aware of your physical surroundings. Alternatively, turn the dial all the way up to “enter the matrix” and be fully immersed in a virtual world.</p><h4>visionOS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KnqA80bou1VVPEePXrbvlA.png" /><figcaption>visionOS home screen. Image credit: <a href="https://www.apple.com/apple-vision-pro/">Apple</a>.</figcaption></figure><p>The name “visionOS” apparently didn’t come easily to Apple. Pre-WWDC rumors and even snippets in several released session videos and documentation actually refer to the operating system as “xrOS”. No doubt, Apple was uneasy about the name “xrOS” and it’s close association with the existing XR/VR/AR/MR technologies, opting to change the name to “visionOS” at the last minute.</p><p>Version-wise, visionOS will be starting at a true 1.0 release. It’s interesting, given that iPadOS and tvOS split off from iOS several years ago, but retained the existing OS version number. All 3 of these operating systems will be on version 17 in the fall. However, with visionOS, Apple chose to give it a fresh start at version 1.0. It will be interesting to see how much of the underlying technologies and interactings visionOS pulls from iOS and macOS vs what gets entirely reimagined or rebuilt from the ground up.</p><p>While visionOS is a new Apple platform and OS, including a new App Store, it will still have a familiar look and feel to Apple’s other operating systems. We can already see that UI elements and interactions take heavy inspiration from iOS, iPadOS, and tvOS. The Focus Engine from tvOS provides a natural mechanism enabling you to automatically highlight/select elements as you look at them. All of this serves to enable what Apple calls “spatial computing”.</p><h3>Spatial Computing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*2TAXdmTlv1NNXuSDOgiVbQ.png" /><figcaption>Common visionOS gestures. Image credit: <a href="https://developer.apple.com/videos/play/wwdc2023/10073/">Apple</a>.</figcaption></figure><p>“Spatial computing” is how Apple is describing the experience of using a Vision Pro. Touted as a totally new computing paradigm, Apple is heavily influencing the way users will learn how to interact with the system, much like they did with the introduction of multi-touch devices back in the day and features such as pinch-to-zoom, flick-to-scroll, and the virtual keyboard. I expect that these new gestures and interactions will likely start to become standard across the industry.</p><p>Instead of a keyboard and mouse or a thumb/finger, the primary way you interact with the system will be using your eyes, fingers, and sometimes your voice. Unfortunately, the device can’t read your thoughts yet, so you still need a keyboard (virtual or physical) for typing unless you want to use the text-to-speech capabilities that are now built-in to Apple’s operating systems. However, with the speed and precision that seems to be enabled by being able to look and pinch to interact with elements, this may be as close as we come to being able to accomplish tasks simply by thought. Only brain-computer interfaces like Neuralink can offer significant improvements from here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*9lcalPw-fg6i5yWepi3upg.png" /><figcaption>3D volumes alongside 2D windows in the “shared space”. Image credit: <a href="https://developer.apple.com/visionos/">Apple</a>.</figcaption></figure><p>In addition to new gestures, the other primary aspect of spatial computing will by the variety of app experiences enabled by the different levels of immersion. Apple splits the app experiences into 2 categories — those that occupy the “shared space”, and those that occupy the “full space”. In the shared space, users interact with windows and volumes. Windows are 2-dimensional, much like what you’re used to with a conventional desktop experience. Volumes are 3-dimensional scenes that live alongside your windows in the shared space. The full space is when you’re fully immersed in an app, and its content takes over everything you see. As far as adopting both levels of immersion, we will have to wait and see if application developers are compelled to introduce both types of experiences into their apps.</p><h3>Downsides?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*_kMWumMvqxVEvEK5vo9ExQ.png" /><figcaption>Digital persona generated from Vision Pro face scane. Image credit: <a href="https://developer.apple.com/videos/play/wwdc2023/101/?time=4837">Apple</a>.</figcaption></figure><p>With as much advanced technology and new experiences this product promises to bring, could there really be any drawbacks that we need to watch out for? I think the first drawback that’s obvious to many people is the cost. At a starting price of $3500, it’s definitely prohibitive to mainstream adoption. We’ll likely see a slow ramp in popularity for at least a couple of hardware versions as capabilities improve and the price drops. Maybe in a few years, we’ll see an “Apple Vision” (non-pro) headset introduced for a cheaper price, which would definitely help make the device available to more people.</p><p>You also have to remember that this is technically a first-generation Apple product. Historically, first-gen Apple products do tend to be a bit underpowered. For instance, think back to the first iPhone, iPad, and Apple Watch models. Compared to just 1 or 2 hardware versions later, those original devices were frighteningly slow. With the Vision Pro, the processing power does look to be adequate, but that seems to come at the expense of battery life. Apple is advertising only a 2 hour runtime, which means that you’ll probably want to stay tethered to a charger most of the time when using it. This will be the main early adopter tax that you’ll pay, but the capabilities certainly do still make it a compelling product.</p><p>Although we don’t know for sure, one other likely drawback to the device will be its lack of support for other VR platforms. Personally, I don’t own a VR headset right now, so it would be great if I could purchase a Vision Pro and use it on other VR platforms like SteamVR for PC gaming or Facebook’s Metaverse. I wouldn’t bet on these to be compatible options anytime soon, but we can still dream.</p><p>The social aspect is also something to consider here. For better or worse, everyone’s eyes are already glued to their phones much of the time these days; now we’re aiming to glue everyone’s phones to their eyes. We may also experience some <a href="https://en.wikipedia.org/wiki/Uncanny_valley">uncanny valley</a> effects. Will the virtual eyes that get displayed on the external screen be weird or okay? How about the virtual persona that gets used in place of your actual video feed when taking a video call while wearing the headset? Will the face-scanning capabilities provided by the device generate realistic looking avatars or will they be creepy? Popular video conferencing solutions like Teams and Zoom have already started introducing virtual personas, so maybe it will become the norm and all work out in the end.</p><h3>What’s Next?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*bP9-89E1QaRckqq675R7pg.png" /><figcaption>Standard visionOS UI components available to designers and developers. Image credit: <a href="https://developer.apple.com/visionos/planning/">Apple</a>.</figcaption></figure><p>If you’re an app developer, you can actually already start developing visionOS apps. The visionOS simulator is already included in the latest beta versions of Xcode 15 and you can even already submit visionOS apps to Apple for approval. It’s important to remember that this is a new platform with a new App Store, which doesn’t happen very often. Now is your chance to get in on the ground floor, so get your fart apps and flashlight apps ready!</p><p>The other big question on everyone’s minds is whether or not this will be the tipping point for VR. Will this finally be the thing that starts to get everyday consumers excited for VR types of experiences? It will be interesting to see if we see widespread use in public like we do for iPhone/iPads, AirPods, and Apple Watches, or if VR products continue to remain “at home” devices. Also, how far will people push the boundaries when using the Vision Pro? Will we see people running or working out with it, or even questionable activities like driving with it? 😬</p><p>Finally, will the Vision Pro actually change the way we compute day-to-day? Will I eventually reach for the headset vs my MacBook when its time to get work done? I expect that it will likely depend on my intended use case much of the time, but the iPad was always poised to be a laptop replacement, but has never quite lived up to that promise for me.</p><p>Regardless of the unknowns, the Apple Vision Pro and visionOS represent a significant step forward in augmented and virtual reality technologies. Whether you like it or not, the age of spatial computing is upon us, and with it, we are one step closer to living in <a href="https://en.wikipedia.org/wiki/Cyberspace">Cyberspace</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65592d7a1342" width="1" height="1" alt=""><hr><p><a href="https://medium.com/atlas/spatial-computing-with-apple-vision-pro-the-final-frontier-65592d7a1342">Spatial Computing with Apple Vision Pro — The Final Frontier?</a> was originally published in <a href="https://medium.com/atlas">Atlas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Design-First in Practice]]></title>
            <link>https://medium.com/atlas/api-design-first-in-practice-bce3797744f0?source=rss-6a77f6e4f041------2</link>
            <guid isPermaLink="false">https://medium.com/p/bce3797744f0</guid>
            <category><![CDATA[api-design]]></category>
            <category><![CDATA[api-first]]></category>
            <category><![CDATA[api-first-design]]></category>
            <category><![CDATA[api-development]]></category>
            <dc:creator><![CDATA[Tyler Milner]]></dc:creator>
            <pubDate>Mon, 09 Jan 2023 16:52:52 GMT</pubDate>
            <atom:updated>2023-01-23T16:31:01.715Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EDtbRRLhuLMJIyXsQK00XQ.jpeg" /></figure><p>Many in the API community are aware of the concept of “API First”, but most articles I see on the subject simply describe what API First is and some of its benefits. Of course, learning about API First and convincing your colleagues to adopt an API First approach to developing features and applications is half the battle, but what does the actual implementation look like? In this post, we’ll walk through the details of how you might implement an API <em>Design-First</em> approach, which is one of the many flavors of the broad API First concept.</p><h3>API Design-First — A Quick Refresher</h3><p>In short, API Design-First is a way of developing application features where the design and shape of the API is considered before any frontend or backend development actually begins. A top-down approach is typically followed where the Experience Design (XD) drives the needs and capabilities of the API. By iterating on the contract and interactions between the frontend and backend, both teams get a chance to become familiar with what the API will look like before implementation, which leads to a smooth and natural integration process. For more information on API First, API Design-First, and its many other variations, check out these awesome articles by some of the top API platforms:</p><ul><li>Swagger — <a href="https://swagger.io/resources/articles/adopting-an-api-first-approach/">Understanding the API-First Approach to Building Products</a></li><li>Stoplight — <a href="https://blog.stoplight.io/api-first-api-design-first-or-code-first-which-should-you-choose">API-First, API Design-First, or Code-First: Which Should You Choose</a></li><li>Postman — <a href="https://www.postman.com/api-first/">Guide to API-First</a></li></ul><h3>Process Overview</h3><p>Like much of the typical development lifecycle, API Design-First follows a “design and build” process to produce iterations of features. At a high-level, the process looks something like the following:</p><figure><img alt="A high-level flow diagram for the API Design-First design and build process." src="https://cdn-images-1.medium.com/max/1024/1*prmIGWk_WYLIvYyCL0ZZhA.png" /><figcaption>A high-level flow diagram for the API Design-First design and build process.</figcaption></figure><h4>XD Artifact Handoff</h4><figure><img alt="XD artifact handoff — wireframe or hi-fi screen designs." src="https://cdn-images-1.medium.com/max/380/1*L_7GAwKmuCBg0A0D9gFukA.png" /><figcaption>XD artifact handoff — wireframe or hi-fi screen designs.</figcaption></figure><p>The process begins with some sort of handoff of an XD artifact, whether that be a wireframe or hi-fi screen design of some other aspect of a user experience flow or feature. While waiting for an XD artifact to be produced and finalized is not strictly necessary, we find that following a top-down approach generally leads to a better developer and user experience by enabling the powerful concept of <a href="https://medium.com/atlas/experience-apis-upgrading-the-experience-for-customers-and-developers-da5e0527947f">Experience APIs</a>.</p><h4>API Domain Definition</h4><figure><img alt="Define API domain(s)." src="https://cdn-images-1.medium.com/max/232/1*b4RCRZEb_Ly7KcGTLXF1ow.png" /><figcaption>Define API domain(s).</figcaption></figure><p>Armed with the XD artifact, the core API design process begins with defining the underlying API domain(s) necessary to support the feature. This might already exist, in the case of something like an existing microservice, or it’s possible that an entirely new API concept might need to be created. For instance, while making your way through the design process for an eCommerce application, you might end up defining API domains like “Account”, “Categories”, “Products”, “Ordering”, etc.</p><h4>API Endpoint Definition</h4><figure><img alt="Define API endpoint(s)." src="https://cdn-images-1.medium.com/max/228/1*4E8G-ravejWFoKO8EnDxAw.png" /><figcaption>Define API endpoint(s).</figcaption></figure><p>Once you’ve established the proper API domain for a feature to live, you can begin outlining the endpoints that will be necessary to bring that feature to life. In terms of a REST API, this would be the resources that make up your API. It’s important to keep things high-level at this stage so just describing the HTTP method and endpoint name/structure are all that’s necessary. For instance, continuing with the eCommerce application example, some endpoints you might define for the “Products” API might be things like GET /products?category={category} to retrieve all of the products for a given category and GET /products/{productId} to get the details for a specific product.</p><h4>Request/Response Definition</h4><figure><img alt="Define Request/Response Details." src="https://cdn-images-1.medium.com/max/230/1*AfzJOqOBUzB2ohyq8xQYvA.png" /><figcaption>Define Request/Response Details.</figcaption></figure><p>After establishing an API domain and its basic resources and actions, you can start to iron out the details of the request and response structures for each endpoint. The reason we’ve waited until now to start putting these details together is because API contract design can sometimes be an iterative process in the early stages of a new feature or product. You want to give yourself room to explore various combinations of API domains and shapes before spending time doing the majority of the work to describe and document the API.</p><p>In addition to things like the JSON schemas used in the requests and responses, you’ll also want to take the time to come up with helpful descriptions for other API components like endpoints, schemas, headers, etc. If necessary, you can also create supporting documentation pages around concepts like authentication, pagination, caching, or even a domain-specific concept like details about the “cart” functionality in the case of the eCommerce example.</p><p>While it’s possible to go low-tech here by simply describing the API details in something like a Word or markdown document, it is advisable to use some sort of machine-readable specification format like <a href="https://www.openapis.org/">OpenAPI</a> (formally known as Swagger). Doing so allows you to take advantage of modern tooling that will make it much easier to create consistent API contracts as well as do things like automatically generate documentation pages, mock servers, and helper libraries.</p><h4>Request/Response Mapping</h4><figure><img alt="Map request/response to design." src="https://cdn-images-1.medium.com/max/240/1*LQUPPIwc1QeYlm14aU7wrw.png" /><figcaption>Map request/response to design.</figcaption></figure><p>Once the details of an API are in place, you’re ready to begin coding, right? Wrong! Just as developing quality software is enabled by writing unit tests, writing quality API contracts is enabled by performing some sort of mapping exercise. Doing so gives you an opportunity to quickly “test” your specification and check your work before handing it off to development teams to implement. A basic mapping document might look something like the following, where you put the XD screen designs side-by-side with the details of the endpoint(s) that will power that feature:</p><figure><img alt="API design mapping document that shows XD screen designs next to API endpoint and response structure." src="https://cdn-images-1.medium.com/max/1024/1*CF3nSszdVEja73zbGK1QWg.png" /><figcaption>API design mapping document that shows XD screen designs next to API endpoint and response structure.</figcaption></figure><p>While you do sort of go through this process in your head when initially describing the API, doing it “on paper” really puts the API design to the test. The main idea is to try to find as many gaps, inconsistencies, or awkwardness in the intended usage of the API. Of course, you could also write code that exercises the API against a mock service, but it’s not strictly necessary unless you want to go the extra mile to test or prototype things out before publishing.</p><h4>API Specification Versioning &amp; Publishing</h4><figure><img alt="Increment API specification version number and publish API specification." src="https://cdn-images-1.medium.com/max/240/1*viCkOzaoVrxS6fDSWMrKgA.png" /><figcaption>Increment API specification version number and publish API specification.</figcaption></figure><p>Once an API concept has been fully explored and the details defined, it’s time to introduce or increment the version of the API contract. Implementing good versioning practices, such as <a href="https://semver.org/">semantic versioning</a>, is critical to ensuring that consumers of the API are not caught by surprise when breaking changes are made to the spec. This is just as much true early on in the development process as it is when the API has already been released to production. Early in the lifecycle of an API, development teams may be consuming pre-release versions of an API that are rapidly changing and evolving as requirements are finalized and iterated upon. Building some level of trust that breaking changes in the API can be easily identified and planned for will lead to much happier and productive development teams.</p><p>Once an API contract has been properly versioned, it can then be published and made available for others to view. This may happen in some sort of automated way, such as a system parsing an OpenAPI document and auto-generating the corresponding HTML pages to render the documentation. It may also be as simple as uploading the document to a file server or emailing it to colleagues.</p><h4>API Specification Review &amp; Acceptance</h4><figure><img alt="Review API specification with stakeholders and API specification acceptance." src="https://cdn-images-1.medium.com/max/400/1*pZCmxMV1K2IIY6Lvyjc5Eg.png" /><figcaption>Review API specification with stakeholders and API specification acceptance.</figcaption></figure><p>Once an initial version or update to an API design has been published, it’s critical to solicit feedback from other stakeholders involved in the creation or consumption of an API. While doing things like the mapping exercise is meant to reduce the amount of potential rework that might be necessary, there’s always the possibility that you forgot to consider a certain scenario or that stakeholders just don’t like the way something is designed. This may necessitate an iteration on the API contract.</p><p>Incorporating feedback might be as simple as renaming some endpoints or properties, or it might be more involved. For complex features, it’s possible that you may end up needing to go back and rethink the domains or reorganize shapes of the API. Naturally, any updates made to the contract should then run through the remaining steps of the API design process. At a minimum, updated mapping documents and associated documentation should be produced, along with a stakeholder re-review of the now updated API designs. Once all feedback has been addressed, the API contract can be considered “accepted” and coding can begin.</p><h4>Build Handoff</h4><figure><img alt="Frontend builds to spec and backend builds to spec." src="https://cdn-images-1.medium.com/max/270/1*oaeZWOnr44GSaN8WDOX8Og.png" /><figcaption>Frontend builds to spec and backend builds to spec.</figcaption></figure><p>Once an API has been identified, described, and its interface agreed upon, both frontend and backend development can begin in parallel. By utilizing mocking techniques, frontend developers can reliably develop features without a working backend. Backend developers should also have a clear understanding of the API contracts that they need to fulfill. When the backend code comes online, things should “just work” for the frontend. While often times, this can be more a dream than a reality, it is made much easier to achieve by having a precise API specification that can be used to test and verify the behavior of the implemented API.</p><h3>Conclusion</h3><p>I hope this article helps to bring some clarity as to what an API Design-First process might look like for your team. Even if you don’t follow these steps exactly, the end result should be the same. API Design-First enables a smooth development experience by carefully considering the needs of the user as well as incorporating feedback from development teams early and often. All of this happens <em>before</em> coding begins, which helps to minimize the cost associated with changes to functionality or clarification of requirements.</p><p>In a <a href="https://medium.com/atlas/api-design-first-tooling-150f2860673b">future post</a>, we’ll take a look at some essential tooling that enables a good API Design-First experience. Until then, what do you think? Have you implemented an API Design-First process for your team or company? What have you found that works or doesn’t work? I’d love to hear your thoughts! Feel free to comment below or contact me at <a href="/service/mailto:tyler.milner@bottlerocketstudios.com">tyler.milner@bottlerocketstudios.com</a> to chat about all things API First.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bce3797744f0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/atlas/api-design-first-in-practice-bce3797744f0">API Design-First in Practice</a> was originally published in <a href="https://medium.com/atlas">Atlas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Design-First Tooling]]></title>
            <link>https://medium.com/atlas/api-design-first-tooling-150f2860673b?source=rss-6a77f6e4f041------2</link>
            <guid isPermaLink="false">https://medium.com/p/150f2860673b</guid>
            <category><![CDATA[api-first]]></category>
            <category><![CDATA[api-first-design]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[api-design-tools]]></category>
            <category><![CDATA[api-development]]></category>
            <dc:creator><![CDATA[Tyler Milner]]></dc:creator>
            <pubDate>Mon, 09 Jan 2023 16:52:21 GMT</pubDate>
            <atom:updated>2023-01-23T16:30:13.891Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3WlaCvCS1FJmtQFR38FtAw.jpeg" /></figure><p>In a <a href="https://medium.com/atlas/api-design-first-in-practice-bce3797744f0">previous post</a>, we took a look at what an API Design-First process looks like in practice. While there’s technically no need for fancy tooling to get started with API Design-First, making use of modern software development tools can make the process much easier, faster, and more reliable. In this post, we’ll walk through some of the tools you might consider to help you on your API journey.</p><h3>Ticketing System</h3><figure><img alt="Jira logo" src="https://cdn-images-1.medium.com/max/460/1*ySWzUyEny6pZaYedpPSItQ.png" /></figure><p>As with any other aspect of software development, having a place to create and track tickets is critical. You should treat API design just like any other aspect of the product you’re building. Tickets should be created for putting together the initial designs of APIs as well as defects or updates to the API contracts. They should then flow through your team’s standard workflow, such as “Todo”, “In Progress”, and “Review/QA”, before moving to “Done”. Any type of ticketing system should work, whether it be fully-featured products like <a href="https://www.atlassian.com/software/jira">Jira</a> or <a href="https://azure.microsoft.com/en-us/products/devops/#overview">Azure DevOps</a>, or lightweight alternatives like <a href="https://trello.com/">Trello</a>.</p><h3>XD Handoff</h3><figure><img alt="Zeplin logo" src="https://cdn-images-1.medium.com/max/400/1*anavhRQ6dYRxeBYIqoYaCA.png" /></figure><p>It’s critical that a product or system be used for making XD designs and flows available to API designers. One of our favorite tools for the job is <a href="https://zeplin.io/">Zeplin</a>, but other tools like <a href="https://www.figma.com/">Figma</a> and <a href="https://miro.com/">Miro</a> can also be used. Ideally, you want to make it easy to find relevant screens or flows as well as keep track of changes over time so that any updates can be incorporated into the API designs.</p><h3>Diagramming</h3><figure><img alt="Lucidchart logo" src="https://cdn-images-1.medium.com/max/461/1*c6Pe8Qcrvoq5dIogRtFA1w.jpeg" /></figure><p>By utilizing diagramming tools, you can more easily digitally brainstorm the shape and concepts for an API as well as help to communicate those ideas though things like Request/Response Mappings and comprehensive user flows. While it’s likely that most general-purpose diagramming applications will work, it’s helpful to use ones that are flexible in terms of their workspace size and document formats that can be imported. <a href="https://www.lucidchart.com/pages">Lucidchart</a> is one such tool that offers an infinitely expanding canvas as well as effortlessly imports supporting artifacts like XD screen design images. Other tools like <a href="https://miro.com/">Miro</a> and <a href="https://www.microsoft.com/en-us/microsoft-365/visio/flowchart-software">Visio</a> may work as well.</p><h3>Source Control Management (SCM)</h3><figure><img alt="GitHub logo" src="https://cdn-images-1.medium.com/max/384/1*JDGZTKXbXU45XVi_OXvvlw.png" /></figure><p>As any developer knows, source code tooling backed by a version control system, like Git, is critical to the productivity and stability of a codebase. By treating your API designs as code, you can obtain many of these same benefits. API designers can create branches where they can make updates to the specs and documentation and then utilize Pull Requests (PRs) to get feedback before making the changes available for everyone to view.</p><p>Along with a repository, some sort of Continuous Integration (CI) system is very helpful. The CI will be used to perform automated checks against your specifications, much like unit tests are used for ensuring code quality of applications. Tools like <a href="https://github.com/stoplightio/spectral">Spectral</a> can be used to lint OpenAPI documents, enforcing consistency, quality, and other API design standards.</p><p>Most SCM platforms these days bundle both version control and CI together, which make it easy to get up-and-running. Simply choose the one that you’re most familiar with or has the features you want. Personally, I’ve had great success with both <a href="https://github.com/">GitHub</a> and <a href="https://azure.microsoft.com/en-us/products/devops/#overview">Azure DevOps</a>, but I’m sure other platforms like <a href="https://about.gitlab.com/">GitLab</a> or <a href="https://bitbucket.org/">Bitbucket</a> will work just as well.</p><h3>API Specification Authoring</h3><figure><img alt="Stoplight logo" src="https://cdn-images-1.medium.com/max/422/1*z2hPTte7s4z_DUXagJkaZA.png" /></figure><p>There are several tools that can help make the process of putting together an OpenAPI specification easier. To-date, I’ve yet to find anything that outclasses the API authoring experience that <a href="https://stoplight.io/">Stoplight</a> provides. Their <a href="https://stoplight.io/studio">Studio</a> desktop app is like an Integrated Development Environment (IDE) for creating API specs. The graphical interface streamlines the ability to create API components while also allowing you to switch to editing the underlying raw YAML or JSON code when necessary. It also integrates nicely with <a href="https://github.com/stoplightio/spectral">Spectral</a> so that your API specs are constantly linted for syntax errors and best practices.</p><p>Another great Stoplight feature is the way that it makes it effortless to visually see the various building blocks of your APIs, which helps enable code reuse and consistency throughout your APIs. The Stoplight web presence also acts as a portal for your API specifications, neatly rendering the associated documentation and making it easy to share with others. In addition to Stoplight, there are also other API platforms that offer much of the same functionality, such as <a href="https://www.postman.com/">Postman</a> and <a href="https://swagger.io/tools/swaggerhub/">SwaggerHub</a>.</p><h3>Shared Knowledge Space</h3><figure><img alt="Confluence logo" src="https://cdn-images-1.medium.com/max/600/1*xOGCTb9V998jGLMsJO3gLQ.png" /></figure><p>While ideally all of your API contracts and documentation should live together, there may occasionally be a need to add supporting documentation in some sort of shared knowledge space or wiki such as <a href="https://www.atlassian.com/software/confluence">Confluence</a> or <a href="https://www.microsoft.com/en-us/microsoft-365/sharepoint/collaboration">SharePoint</a>. This will depend entirely on your team’s workflow and needs, but things like dedicated pages that give an overview of an API or feature along with XD artifacts and any other critical information can be helpful.</p><h3>API Client</h3><figure><img alt="Postman logo" src="https://cdn-images-1.medium.com/max/434/1*9_6251dzENGUMzDeyBzkYQ.png" /></figure><p>Another piece of tooling that’s helpful in following through with the API design process is an API client. Simply put, this is an application that can execute API calls. The most popular API client is by far <a href="https://www.postman.com/">Postman</a>, but other alternatives like <a href="https://paw.cloud/">Paw</a>, <a href="https://insomnia.rest/">Insomnia</a>, and <a href="https://www.telerik.com/fiddler">Fiddler</a> also exist.</p><p>While you won’t necessarily use an API client to create API specifications or documentation, it can be useful to create shared workspaces that others can use to test and get more familiar with using the API. Many API clients have the ability to import an OpenAPI specification, which makes getting started that much easier. You don’t need to wait until the backend team has finished development either. Most API platforms automatically generate mock servers from your API specifications, which you can interact with using an API client like Postman.</p><p>API clients also allow you to write tests against APIs. In addition to basic tests like status code checks, it’s also very helpful to implement contract tests. API contract tests will make sure that the response returned from the server matches the expected response according to the API specification. By implementing contract tests early, you can make it easy to verify that any backend code that gets deployed holds true to the spec, which will ensure a smooth integration experience for the frontend.</p><h3>Conclusion</h3><p>It doesn’t require a lot of fancy tooling to get started with an API Design-First process. Aside from the API-specific authoring tools like Stoplight, it’s likely that you are already familiar with or using many of these tools for your day-to-day software development process.</p><p>Are there any tools that you find invaluable to your own API Design-First process? I’d love to hear your recommendations! Feel free to drop a comment below or email me directly at <a href="/service/mailto:tyler.milner@bottlerocketstudios.com">tyler.milner@bottlerocketstudios.com</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=150f2860673b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/atlas/api-design-first-tooling-150f2860673b">API Design-First Tooling</a> was originally published in <a href="https://medium.com/atlas">Atlas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apple Watch Series 0 to Series 4 — What’s New?]]></title>
            <link>https://medium.com/atlas/apple-watch-series-0-to-series-4-whats-new-1676fe686c11?source=rss-6a77f6e4f041------2</link>
            <guid isPermaLink="false">https://medium.com/p/1676fe686c11</guid>
            <category><![CDATA[apple-watch]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[apple-watch-series-0]]></category>
            <category><![CDATA[wearables]]></category>
            <category><![CDATA[apple-watch-series-4]]></category>
            <dc:creator><![CDATA[Tyler Milner]]></dc:creator>
            <pubDate>Tue, 09 Oct 2018 18:33:50 GMT</pubDate>
            <atom:updated>2018-10-09T18:34:11.660Z</atom:updated>
            <content:encoded><![CDATA[<h3>Apple Watch Series 0 to Series 4 — What’s New?</h3><p>I’ve had an Apple Watch since a few months after it was initially launched in April of 2015. I’m not usually an early adopter of Apple’s first-gen tech, but I feel that they did a great job with the watch. However, with watchOS 5 only supporting Series 1 and higher, I’ll admit that I’m a bit sad that my Series 0 watch has now reached its end-of-life. I know the new watches are supposed to be much faster, but my Series 0 is still chugging along just fine for the tasks I use it for the most — notifications, timers, stopwatch, weather, Siri, and music playback. Having seen watchOS mature to a great state with last year’s watchOS 4 release, I was hoping that the Series 0 would still get the update, but maybe lack some of the fancy new features. Of course, the new screen sizes and thinner profile of the Series 4 would have probably enticed me to upgrade this year anyway, but what are the other improvements I should expect when I strap Apple’s latest smart wearable onto my wrist in the coming weeks?</p><h3>Speed Improvements</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*wSwdUakHgEBfO1nxAsz5hQ.jpeg" /><figcaption>Apple Watch speed improvements showcased from their September 2016 event to their September 2018 event.</figcaption></figure><p>It’s obvious that my new watch will be faster, but how much faster? The Apple Watch Series 0 shipped with Apple’s S1 “System-in-Package” (SiP), which contained a single-core processor that ran at roughly 520 MHz. Apple shipped the Series 1 and Series 2 watches with their S1P and S2 SiP, respectively, which contained a dual-core processor touted as being 50% faster. When Apple introduced the Series 3 watch last year, they marketed the S3 SiP as being 70% faster. With the release of the Series 4 this year, they are now claiming up to a 2x improvement in speed. When you add up the speed improvements over the years, I think it’s safe to say that I should be blown away by how fast this watch will be.</p><p>The move to a 64-bit architecture is also important. Apple dropped support for their 32-bit iPhones and iPads when they introduced iOS 11 last year. I feel as though it’s only a matter of time before they will do the same thing to the Apple Watch.</p><h3>Display</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*LeFjp9hT6YxFYuBw4Pmisg.gif" /><figcaption>Series 3/4 screen size comparison, courtesy of <a href="https://www.apple.com/watch/compare/">Apple</a>.</figcaption></figure><p>The most notable physical upgrade of Apple Watch Series 4 is certainly the display size. Even the smaller 40mm Series 4 watch contains a display that’s slightly larger than my current 42mm Series 0. This means that my new 44mm Series 4 watch should provide me with a significant upgrade in screen real estate. The edge-to-edge nature and rounded corners are also a great aesthetic upgrade.</p><p>It’s important to note that Apple also doubled the brightness of the display to 1000 nits when they introduced Apple Watch Series 2 in September of 2016. This should make it easier to see the screen in bright sunlight compared to my Series 0 (though I’ve never really had an issue with the display’s brightness in the past). I suppose it will also allow me to see a bit better in the dark when I use the app grid/list as a makeshift wrist-mounted flashlight at night. 😁</p><h3>Form Factor</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*u0k--i7KneWslx13wiqAqQ.png" /><figcaption>Series 3/4 thickness comparison, courtesy of <a href="https://www.apple.com/watch/compare/">Apple</a>.</figcaption></figure><p>While never a huge deal, my Series 0 watch always felt a tad on the chunky side. I’m looking forward to the thinner Series 4 watch and hopefully not smacking it on as many surfaces as I clumsily move about my day (though my Series 0 has held up remarkably).</p><p>Another physical improvement that I’m excited about is the inclusion of haptic feedback for the digital crown. This should make it a much more pleasant experience to scroll through lists and reduce the chances of over or undershooting an item when scrolling quickly.</p><h3>Health and Fitness</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iCELwXMjao-FmRBwzCooNA.png" /><figcaption>Taking an ECG on a Series 4 watch, courtesy of <a href="https://www.apple.com/apple-watch-series-4/health/">Apple</a>.</figcaption></figure><p>One of the main features of Series 4 that’s got everybody excited is the ability to take an electrocardiogram (ECG) on-the-go via the new electrical heart sensor embedded into the ceramic back and digital crown. However, since I’m upgrading from a Series 0, I’m also excited to finally be able to take advantage of the heart rate notifications feature. Apple first introduced elevated heart rate detection when Apple Watch Series 2 was introduced in 2016, but the feature was only supported on Series 1 and higher devices. With additional upgrades to the feature in watchOS 5, I’ll also have the piece of mind that my watch will additionally be monitoring for abnormally low heart rates and atrial fibrillation.</p><p>Because I’ll be able to run the latest watchOS 5, I’ll also be able to take advantage of the new automatic workout detection feature. Not only can the watch detect when a workout session begins, it can also automatically classify the workout as running, walking, swimming, elliptical, or rowing. There are also now discrete workout types for yoga and hiking, which should improve calorie burn accuracy when performing those activities.</p><h3>Other Improvements</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HBjNlyVBlTxWbogC.gif" /><figcaption>watchOS 5&#39;s Walkie-Talkie feature in action, courtesy of <a href="https://support.apple.com/en-mz/HT208917">Apple</a>.</figcaption></figure><p>Coming from my Series 0, other net new features that I’m excited about include:</p><ul><li>Built-in GPS</li><li>Water resistant to 50 meters</li><li>Audible Siri (having her talk back to you instead of needing to read the screen — first introduced with Apple Watch Series 3)</li><li>Faster WiFi (W3 wireless chip)</li><li>Built-in cellular (though I opted for the GPS-only version)</li><li>Built-in barometric altimeter</li><li>Louder speaker</li><li>Fall detection (via the improved accelerometer and gyroscope)</li></ul><p>Of course, I touched on some of these above, but there’s also all of the new features in watchOS 5 that I’ll be able to take full advantage of like the Walkie-Talkie app and raise-to-wake Siri.</p><h3>Conclusion</h3><p>Although I’m a little bit disappointed that my Apple Watch Series 0 will not be receiving the latest watchOS 5 update, I feel like Apple has made it worthwhile to upgrade to the latest iteration of their watch hardware. When you add up all of the incremental improvements made over the past 3 years as well as the improved form factor of Apple Watch Series 4, it’s a no-brainer that this new device will be a significant improvement and happily stay attached to my wrist for another 3+ years.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1676fe686c11" width="1" height="1" alt=""><hr><p><a href="https://medium.com/atlas/apple-watch-series-0-to-series-4-whats-new-1676fe686c11">Apple Watch Series 0 to Series 4 — What’s New?</a> was originally published in <a href="https://medium.com/atlas">Atlas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Firebase for Server-Side Swift]]></title>
            <link>https://medium.com/atlas/getting-started-with-firebase-for-server-side-swift-93c11098702a?source=rss-6a77f6e4f041------2</link>
            <guid isPermaLink="false">https://medium.com/p/93c11098702a</guid>
            <category><![CDATA[cloud-firestore]]></category>
            <category><![CDATA[server-side-swift]]></category>
            <category><![CDATA[vapor]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Tyler Milner]]></dc:creator>
            <pubDate>Wed, 07 Mar 2018 14:15:15 GMT</pubDate>
            <atom:updated>2020-01-24T20:14:33.005Z</atom:updated>
            <content:encoded><![CDATA[<h4>Connecting Swift Vapor to Firebase’s Cloud Firestore Database</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*VSa0Vo9SaifJ95_ef-umWg.png" /></figure><p>The Firebase suite of tools is awesome. It’s great to have so many useful development services bundled under one roof, and the ability to get started for free is great! Firebase offers SDKs for several platforms to communicate with their services, including iOS. However, the iOS SDK is heavily coupled to the iOS application lifecycle and thus not usable in a server-side Swift environment. Luckily, Firebase offers a REST API which gives us an avenue to use their services when developing a server in Swift. Having done just that recently, this post outlines the steps needed to get started with the Firebase REST API in a server-side Swift environment. I’ll be connecting a Swift Vapor app to Firebase’s new Cloud Firestore technology, but the general process should apply to any other server-side Swift framework and Firebase service.</p><h3>The Tech Stack</h3><h4>Cloud Firestore</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*XWe7Dh81jXtdk34TW2mbxQ.png" /><figcaption>Firebase Cloud Firestore</figcaption></figure><p><a href="https://firebase.google.com/docs/firestore/">Cloud Firestore</a> is Firebase’s “new and improved” NoSQL cloud database. As with their previous product, <a href="https://firebase.google.com/docs/database/">Firebase Realtime Database</a>, Cloud Firestore syncs data in realtime across clients and offers first-class support for offline mode.</p><h4>Cloud Firestore vs Realtime Database</h4><p>If you’ve used Firebase’s Realtime Database product in the past, you may be wondering how Cloud Firestore is different. The <a href="https://firebase.google.com/docs/firestore/rtdb-vs-firestore">Firebase documentation goes into more detail</a>, but it basically boils down to Firebase improving upon the successes of the original Realtime Database product. The older Realtime Database required denormalization and data flattening techniques to prevent bottlenecks as your database grew and evolved. Cloud Firestore improves upon this by offering richer, faster queries and better scalability.</p><p>So if Cloud Firestore is an improved version of Realtime Database, is Realtime Database even relevant anymore? The answer is yes. The real strength of the Realtime Database continues to be its speed. If you need to optimize your product for efficient, low-latency syncing, then you will probably want to use Realtime Database instead of Cloud Firestore. That’s not to say that Cloud Firestore won’t do the job. It still syncs things super fast (within milliseconds).</p><h4>Vapor 2.x</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*MofpxVA2unzKHUQ4Vq3DxA.png" /><figcaption>Server-side Swift Vapor</figcaption></figure><p><a href="https://vapor.codes/">Vapor</a> is one of the many server-side Swift libraries on the market. I feel they’ve done a great job keeping things simple to understand and making it easy to get started with server-side Swift development. They even recently launched <a href="https://vapor.cloud/">Vapor Cloud</a>, which makes it ridiculously easy to deploy your server into the real world. It’s even free for small projects! For this project, I used Vapor 2.x since Vapor 3 was still in beta when I started.</p><h3>The Sample Project</h3><p>I’ll be using these technologies to implement a simple proof-of-concept for utilizing server-side Swift to implement custom backend logic while relying on Firebase for realtime updates to client apps. For this demo, the server will simply be generating a random number every 60 seconds and then publishing that number to the Cloud Firestore database along with the date that it will generate the next random number. When everything is up and running, the client app will look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*_e-MBU29Vr1zcjAX5GyQqQ.gif" /><figcaption>The iOS client app for this sample project</figcaption></figure><h3>Setting up Firebase</h3><p>The first thing you’ll want to do after creating your Firebase project is to enable Cloud Firestore. This is easy enough to do. Open your Firebase project and navigate to Develop → Database and turn it on:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*Pii76-7UVPNLCbrXUQ7jdg.png" /><figcaption>Enabling Firebase Cloud Firestore</figcaption></figure><p>Once enabled, you’ll see an empty database that looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yvFDb0Lw2kwPOajGPx2ATA.png" /><figcaption>Empty Cloud Firestore database</figcaption></figure><h3>Connecting to Firebase</h3><p>Now that we’ve got Cloud Firestore enabled for our project, how can we connect to it? As I mentioned above, the Firebase iOS SDK is off the table. Perhaps the SDK will someday be compatible with server-side Swift, but the Firebase team <a href="https://groups.google.com/d/msg/firebase-talk/l2T0IZwwimg/utRwLTT-EwAJ">currently has no concrete plans in place</a>.</p><p>Since we can’t use the iOS SDK, our options for connecting to Cloud Firestore from Vapor are either using the <a href="https://firebase.google.com/docs/firestore/use-rest-api">REST API</a> or the <a href="https://firebase.google.com/docs/firestore/reference/rpc/">RPC API</a>. Since I don’t know enough about RPC yet, we’ll be using the REST API for this example.</p><p>If you’re using the older Realtime Database product, I should mention that you actually have another option. There exists an open source Swift library called <a href="https://github.com/gtchance/FirebaseSwift">FirebaseSwift</a> that provides some conveniences for connecting to Realtime Database from a server-side Swift environment. However, you’ll still need to manually generate and manage your Google OAuth token, which I’ll talk about in a bit.</p><h3>Cloud Firestore REST API</h3><p>Using the Cloud Firestore REST API is as simple as:</p><ul><li>Authenticating with Google to receive a server-to-server access token.</li><li>Using that access token to read/write data to the Cloud Firestore database.</li></ul><h3>Google Server-to-Server OAuth</h3><h4>Authentication Options</h4><p>There are three ways that you can authenticate with Google to receive a server-to-server access token:</p><ul><li>Use one of the <a href="https://developers.google.com/api-client-library/">10 official client libraries</a>.</li><li>Manually follow <a href="https://developers.google.com/identity/protocols/OAuth2ServiceAccount">Google’s server-to-server OAuth 2.0 steps</a>.</li><li>Use the gcloud command-line tool.</li></ul><p>Although Google strongly encourages you to use one of their client libraries, Swift is not supported yet. 😔</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O7Yzq73Hjbmo8u92pVX9XA.png" /><figcaption>Google’s recommendation to use one of their client libraries to authenticate</figcaption></figure><p>This means that we’ll need to manually implement the OAuth process. I haven’t looked into the gcloud command-line tool, but it seems to me that it’d only really be useful for generating one-off tokens for testing.</p><h4>Authentication Prerequisites</h4><p>In order to authenticate with Google, you’ll need to use a Google “service account”. A service account is an account that belongs to your application itself rather than an individual user of your app. A service account is composed of two things:</p><ul><li>A unique email address, which is auto-generated for you by Google.</li><li>A public/private key pair.</li></ul><h4>Obtaining a Google Access Token</h4><p>So we’ve established that we’ll need to manually follow Google’s OAuth process. How does that work? The process can be summarized in three steps:</p><ul><li>Create a JSON Web Token (JWT), signed with your service account’s private key.</li><li>Use the JWT to request an access token from the Google OAuth 2.0 Authorization Server.</li><li>Handle the JSON response from the Authorization Server.</li></ul><p>A sequence diagram of this flow looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*9sDvRXmjUNKwOJH7LN52gA.png" /><figcaption>Google server-to-server OAuth process</figcaption></figure><p>I should note that <a href="https://developers.google.com/identity/protocols/OAuth2ServiceAccount#authorizingrequests">Google’s documentation</a> again calls out that they’d really like for you to use one of their client libraries to authenticate. I think they’re trying to tell us something…🤔</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NdCXD0hvnXy9zxLKuc--Uw.png" /><figcaption>Google again recommending to use their client libraries for authentication</figcaption></figure><p>Since there’s no Swift-compatible Google authentication library available, we’ll just have to ignore Google’s persistent attempts to dissuade us from manually implementing their OAuth flow. But first, a quick crash course on JWTs…</p><h3>JWT — A Quick Refresher</h3><p>A JWT, pronounced “jot”, is basically just a piece of data composed of three parts:</p><ul><li>A “header”, which specifies the format of the token and the signing algorithm used.</li><li>A “payload” (or “claims”) which holds information about the token, including things like which user the token represents, what permissions (scopes) they have available, and the token lifetime.</li><li>A “signature”, which is a cryptographic signature of the header and claims appended together.</li></ul><p>Each part of the JWT is base64 url-encoded and then appended together with periods to form the final representation of the JWT. Overall, the process looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70mL3p5TV-rPeQXvKg2vpQ.png" /><figcaption>How a JWT is formed</figcaption></figure><p>It’s important to note that even though it may look like it, a JWT is <strong>not encrypted</strong>. This means that anyone can read the contents of the “claims”. If you are ever creating JWTs for your own purposes, don’t store any sensitive information in them. The cryptographic signature of the JWT simply allows the entity that issued the JWT to verify the integrity of the data. If a party tries to modify any of the information in the “header” or “claims”, then the signature will indicate that the data is invalid and the issuer can reject the token.</p><h3>Generating the Google OAuth JWT</h3><p>So how do we generate the Google OAuth JWT using Vapor? In order to generate the JWT, we need to satisfy two prerequisites:</p><ul><li>Obtain the Google Service Account credentials that I mentioned earlier (specifically the private key).</li><li>Configure the Vapor project by adding the JWTProvider helper library and configuring a Signer with the service account’s private key.</li></ul><h3>Google Service Account Credentials</h3><p>You can manage serve accounts on the <a href="https://console.developers.google.com/permissions/serviceaccounts">Google Service Accounts page</a>, but we can also access the service account associated with our Firebase project through the Firebase Console, which is the process that we’ll follow right now.</p><p>It’s important to note that even though Google generates the public/private key pair for your service account, they don’t keep a copy of the private key. It’s up to you to keep track of it and store it securely.</p><h4>Downloading the Credentials</h4><p>In order to download your service account credentials, first open your project’s settings on Firebase by tapping the gear icon next to “Project Overview” and then selecting “Project Settings”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*UJ24q0-qYKp_0ZmCv3cdEQ.png" /><figcaption>Accessing Firebase project settings</figcaption></figure><p>Next, navigate over to the “Service Accounts” tab and then click on the “Generate New Private Key” button at the bottom:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*qhJh_W-1m2W9levtFP6jzQ.png" /><figcaption>Downloading the service account private key</figcaption></figure><p>This will download a JSON file to your computer, which is Google’s preferred format for distributing these private keys.</p><h4>Credentials JSON Format</h4><p>Open up your service account credentials JSON file. It should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vc0WpfFO_DGKXkgOE2imvw.png" /><figcaption>Google Service Account credentials JSON file</figcaption></figure><p>Notice the private_key field. This is what the Signer in our Vapor app will need to generate and sign the JWTs used for Google’s server-to-server OAuth process.</p><h3>Transforming the Private Key</h3><p>Unfortunately, the private key in its current form will not work for us. The main issue with this version of the key is that it’s just a regular “private key”. What we need is an “RSA private key”. This small detail caused me hours of pain until a friend enlightened me to the fact that there are different <em>types</em> of private keys.</p><h4>Create a File for the Key</h4><p>The first thing we need to do is copy the value of the private_key field in the credentials JSON to its own file. Save this file as GooglePrivateKey.key.</p><h4>Clean up Whitespace</h4><p>If you look at the private key right now, you might notice that there are several \n newline characters:</p><pre>-----BEGIN PRIVATE KEY——<strong>\n</strong>MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDBsMABtSYcQBX1<strong>\n</strong>03xsgbc36ekABgnfKdoJlOVkstpLlv1zpev2grxvCS+VR9D1dbrZJ9QJKfHoyjqT<strong>\n</strong>abvhnxMTdvwVQ94Ohoo0lShSvN6NO94a6Hy8iWSHDZuM4LScPGp9H3eNjdMysQ+L<strong>\n</strong>95xi4qioPndyJzwPcOOzM8WirWe5Osk+vFy4sSvVQFpwaMqvQ35abVVVAydWOF6G<strong>\n</strong>lmliKRiGB5Ueb.C..qdYE3j+o3WhweBw==<strong>\n</strong>——END PRIVATE KEY-----<strong>\n</strong></pre><p>We need to get rid of those by converting them into actual newlines. Go ahead and highlight each \n occurrence and press “Enter” on your keyboard to replace it with a newline. You should end up with something like this:</p><pre>-----BEGIN PRIVATE KEY——MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDBsMABtSYcQBX1<br>03xsgbc36ekABgnfKdoJlOVkstpLlv1zpev2grxvCS+VR9D1dbrZJ9QJKfHoyjqT<br>abvhnxMTdvwVQ94Ohoo0lShSvN6NO94a6Hy8iWSHDZuM4LScPGp9H3eNjdMysQ+L<br>95xi4qioPndyJzwPcOOzM8WirWe5Osk+vFy4sSvVQFpwaMqvQ35abVVVAydWOF6G<br>lmliKRiGB5Ueb.C..qdYE3j+o3WhweBw==<br>——END PRIVATE KEY——</pre><p>If you know of a better way to do this instead of manually, please let me know! I think there’s a way to do this with the sed command on macOS, but I haven’t had time to experiment with it yet.</p><h4>Convert the Private Key into an RSA Private Key</h4><p>Next, use OpenSSL to generate an RSA private key from your newly cleaned up private key:</p><pre>openssl rsa -in GooglePrivateKey.key -out GooglePrivateKey_RSA.key</pre><h4>Prepare RSA Private Key for Use in Vapor</h4><p>We’re almost done transforming this private key into the format we want. The next thing we need to do is convert this RSA private key into a single line. Open up GooglePrivateKey_RSA.key in a text editor and remove all of the newlines so that the entire key is on one line.</p><p>Next, remove the -----BEGIN RSA PRIVATE KEY-----and -----END RSA PRIVATE KEY----- so that we just have the contents of the key itself in a single line. You should end up with something like this:</p><pre>MIIEogIBAAKCAQEAwbDAAbUmHEAV9dN8bIG3N+npAAYJ3ynaCZTlZLLaS5b9c6Xr9oK8bwkvlUfQ9XW62SfUCSnx6Mo6k2m74Z8TE3b8FUPeDoaKNJUoUrzejTveGuh8vIlkhw2bjOC0nDxqfR93jY3TMrEPi/ecYuKoqD53cic8D3DjszPFoq1nuTrJPrxcuLEr1UBacGjKr0N+Wm1VVQMnVjhehpZpYikYhgeVHmwvMPay2ylcerNgQnb81tF8WN8IskLU5igseY/Ayi4Vxvmo2NjfYY5ppROsM/DDZcKgroOhjNLfzeYSHIh3qfI4...Vno4pV3a7cD7aaZjJL+gr1+ipSHiu8BSE+FL+K3hitR6bMGQxZWVc/jfsB+gjx4I4WqLAoGAU+9+PkwKqVqhyR4MrnRrCcpSfhrkD7jkvOWOYoGhBka5r0GvRITP+BKYfcvooDzfXjGgBPFXzIdPlfrNwsUyKf1zARrwLExg+6/PMrWiVVubIuGYzhzrLtYQtF9sBhtgsNNYIkaH2mybgOZ2k45smk98Vug2KnWBN4/qN1ocHgc=</pre><h3>Setting Up Vapor</h3><p>Now it’s <em>almost</em> time to start writing our server-side Swift code. Aren’t you excited?! There’s just a few setup items that we need to take care of first. I’m assuming that you’ve already got Vapor installed and a project created. If not, follow <a href="https://docs.vapor.codes/2.0/getting-started/install-on-macos/">Vapor’s getting started instructions</a>.</p><h4>Adding JWTProvider</h4><p>Add the JWTProvider dependency to your Package.swift file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*xtyXvoUe0VUXm5F_6ypIUg.png" /><figcaption>Adding JWTProvider to your Vapor project’s Package.swift file</figcaption></figure><p>Next, regenerate your Xcode project:</p><pre>swift package generate-xcodeproj</pre><p>or:</p><pre>vapor xcode</pre><p>If it’s not already open, go ahead and open the Xcode project as well.</p><h4>Initialize JWTProvider</h4><p>Open the Config+Setup.swift file and initialize the JWTProvider in the setupProviders() method:</p><pre>/// Configure providers</pre><pre>private func setupProviders() throws {<br>    try addProvider(FluentProvider.Provider.self)<br>    <strong>try addProvider(JWTProvider.Provider.self)<br></strong>}</pre><h4>JWT Config</h4><p>The final step involved with setting up JWTProvider is to create a jwt.json configuration file. Go ahead and make a file called jwt.json in the Config directory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*Wlf7lDdp9FzBUKv6mJcXog.png" /><figcaption>Creating the Config/jwt.json file</figcaption></figure><p>Populate Config/jwt.json with the following contents:</p><pre>{<br>    &quot;signers&quot;: {<br>        &quot;googleOAuth&quot;: {<br>            &quot;type&quot;: &quot;rsa&quot;,<br>            &quot;algorithm&quot;: &quot;rs256&quot;,<br>            &quot;key&quot;: &quot;$GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY&quot;<br>        }<br>    }<br>}</pre><p>Here’s what’s going on in the JSON file:</p><ul><li>A top-level object called signers must be present.</li><li>For this example, we only have one signer called googleOAuth.</li><li>The googleOAuth signer specifies the algorithm and key used to perform the signing.</li></ul><p>Notice that we <strong>did not</strong> paste in that single-line RSA private key that we just created. More on this in just a second, but we’re actually using the syntax for injecting environment variables into the JSON file. There are other options for how you configure your jwt.json file as well. If you’d like to know more about that or JWTProvider, feel free to check out the <a href="https://docs.vapor.codes/2.0/jwt/overview/#custom-signers">Vapor JWT documentation</a>.</p><h4>Vapor Development Process</h4><p>Before we go any further, I’d like to take a moment to discuss my Vapor development process. I’ve found that it’s easiest to get started by putting all of your logic into the Routes.swift file. This way, you can test/trigger your logic by issuing a request to your route using something like <a href="https://www.getpostman.com/">Postman</a>. If you’re route is a GET, then I suppose you could trigger it via your browser as well.</p><p>For this example, I started by creating a POST route called “nextRandom”:</p><pre>import Vapor<br>import JWT<br>import Foundation</pre><pre>extension Droplet {<br>    func setupRoutes() throws {</pre><pre>        post(&quot;nextRandom&quot;) { request in<br>            do {<br>                // ...<br>            } catch {<br>                debugPrint(&quot;\(error)&quot;)<br>                return Response(status: .internalServerError, <br>                                body: &quot;\(error)&quot;)<br>            }<br>        }<br>    }<br>}</pre><h3>Securing the Private Key</h3><p>As I mentioned previously, we need to be extra careful with our private key. In the words of the wise wizard Gandolf:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*cI4xXUr7Vm4PWDK_gJsl3Q.png" /><figcaption>Keep it secret…keep it safe…your private key, that is</figcaption></figure><h4>Just Say No to Source Control</h4><p>I’ll say this just once, but I’ll say it loud:</p><p><strong>NEVER COMMIT YOUR PRIVATE KEY INTO SOURCE CONTROL!</strong></p><p>Consider yourself warned.</p><h4>Setup the Private Key Environment Variable</h4><p>As I mentioned above, the value of the key in our Config/jwt.json file is set to an environment variable. This allows us to keep the key out of source control by injecting it at runtime.</p><p>To set this up, edit your app’sRun scheme and add an environment variable called GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY. Next, paste your single-line RSA private key as the value for GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*n-heXzYaREqLGo1ohsU5CA.png" /><figcaption>Setting up the Run scheme with the GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY environment variable</figcaption></figure><p>Please note that if you’re using a “shared” scheme, <strong>do not</strong> do this! Shared schemes are often committed into source control so you wouldn’t be doing yourself any favors by setting up this environment variable.</p><p>Instead, if you’re using a shared scheme, create your jwt.json file inside of the Config/secrets directory. Just make sure to double-check that the Config/secrets directory is <strong>included</strong> in your .gitignore file so that it’s <strong>excluded</strong> from source control. The default Vapor .gitignore already has this directory excluded:</p><pre># Created by <a href="https://www.gitignore.io/api/vapor">https://www.gitignore.io/api/vapor</a></pre><pre>### Vapor ###<br>Config/secrets</pre><pre>### Vapor Patch ###<br>Packages<br>.build<br>xcuserdata<br>*.xcodeproj<br>DerivedData/<br>.DS_Store</pre><pre># End of <a href="https://www.gitignore.io/api/vapor">https://www.gitignore.io/api/vapor</a></pre><h4>Private Key Gotchas</h4><p>Just a few “gotchas” to be aware of involving your private key:</p><ul><li>Make sure to securely store a copy of your cleaned, single-line RSA private key. This is mainly just a convenience so that you don’t have to reconvert the key from its original JSON file format if you ever need to reconfigure your Xcode project.</li><li>Deleting the Xcode project will wipe out the GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY environment variable. However, simply <em>regenerating</em> the Xcode project is fine.</li><li>Your app will crash on launch if the private key in your Config/jwt.json file is missing or invalid.</li></ul><p>That last point is important. JWTProvider will fail to initialize if it can’t generate a valid RSA private key based on the values in your jwt.json configuration file. If this happens, your Vapor app will crash with a JWT error: Could not create key error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L8bied1ahyk_HRdGlmtZEg.png" /><figcaption>JWTProvider’s crash on launch when it is configured with an invalid RSA private key</figcaption></figure><h3>Authenticating with Google using Vapor</h3><p>Finally, we’ve got all the setup out of the way and can begin writing our server-side Swift code! 🎉 Go ahead and open Routes.swift and get ready to start filling in the implementation of the POST /nextRandom endpoint. If you want to peek ahead to what this route will look like when we’re done, then feel free to take a look at the <a href="https://github.com/tylermilner/VaporFirebaseDemo/blob/feature/basicExample/Sources/App/Routes/Routes.swift">Routes.swift file on the <em>feature/basicExample</em> branch</a>.</p><h4>Creating the Google OAuth JWT</h4><p>Use Vapor’s JSON type to create the JWT headers:</p><pre>// Google OAuth - Create the JWT headers</pre><pre>var headersJSON = JSON()</pre><pre>try headersJSON.set(&quot;alg&quot;, &quot;RS256&quot;)</pre><pre>try headersJSON.set(&quot;typ&quot;, &quot;JWT&quot;)</pre><p>Up next, we’ll create the claims:</p><pre>// Google OAuth - Create the JWT claims</pre><pre>let issuedTime = Date()</pre><pre>let timeToLive: TimeInterval = 60 * 30 // 30 minutes, max is 60</pre><pre>let expirationTime = issuedTime.addingTimeInterval(timeToLive)</pre><pre>var claimsJSON = JSON()</pre><pre>try claimsJSON.set(&quot;iss&quot;, &quot;firebase-adminsdk-notoj@vaporfirebasedemo.iam.gserviceaccount.com&quot;) // the value of &quot;client_email&quot; in the service account JSON</pre><pre>try claimsJSON.set(&quot;scope&quot;, &quot;https://www.googleapis.com/auth/datastore&quot;)</pre><pre>try claimsJSON.set(&quot;aud&quot;, &quot;https://www.googleapis.com/oauth2/v4/token&quot;)</pre><pre>try claimsJSON.set(&quot;exp&quot;, Int(expirationTime.timeIntervalSince1970))</pre><pre>try claimsJSON.set(&quot;iat&quot;, Int(issuedTime.timeIntervalSince1970))</pre><p>Notice that we’ve given our JWT a lifetime of 30 minutes. Feel free to change this value to suit your needs. A smaller value is arguably more secure, and the maximum value that Google will accept is 60 minutes.</p><p>To actually create the JWT, we need to get a reference to the Signer object that represents the “googleOAuth” signer in our jwt.json configuration file. From there, we can create the final, encoded JWT from the headers, claims, and Signer:</p><pre>// Google OAuth - Create the JWT signature</pre><pre>guard let oAuthSigner = self.signers?[&quot;googleOAuth&quot;] else {</pre><pre>    return Response(status: .internalServerError, <br>                    body: &quot;Unable to locate signer&quot;)</pre><pre>}</pre><pre>let accessTokenRequestJWT = try JWT(headers: headersJSON, payload: claimsJSON, signer: oAuthSigner)</pre><pre>let jwtString = try accessTokenRequestJWT.createToken()</pre><h4>Sending the OAuth Request</h4><p>We’ll use Droplet’s client property to perform a POST request onto Google’s OAuth URL using the following URL-encoded form parameters:</p><ul><li>grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer</li><li>assertion=&lt;value of the JWT&gt;</li></ul><pre>// Google OAuth - Authenticate with Google using the created JWT</pre><pre>let oAuthParams = &quot;grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&amp;assertion=\(jwtString)&quot;.urlQueryPercentEncoded</pre><pre><br>let authResponse = try self.client.post(&quot;https://www.googleapis.com/oauth2/v4/token&quot;,</pre><pre>                query: [:],</pre><pre>                [.contentType: &quot;application/x-www-form-urlencoded&quot;],</pre><pre>                oAuthParams,</pre><pre>                through: [])<br></pre><pre>// Google OAuth - Handle the response from Google</pre><pre>switch authResponse.status {</pre><pre>case .ok:</pre><pre>    guard let accessToken: String = try authResponse.json?.get(&quot;access_token&quot;) else {</pre><pre>        return Response(status: .internalServerError, <br>                        body: &quot;Google auth response did not include an access token&quot;)</pre><pre>    }</pre><pre>    // ...</pre><pre>default:</pre><pre>    return Response(status: .internalServerError,<br>                    body: &quot;Unexpected Google auth response: &#39;\(authResponse.status)&quot;)</pre><pre>}</pre><p>A successful response from Google will contain an access_token, which is what we’ll need to provide in our requests to Firebase:</p><pre>{<br>  &quot;access_token&quot; : &quot;1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M&quot;,<br>  &quot;token_type&quot; : &quot;Bearer&quot;,<br>  &quot;expires_in&quot; : 3600<br>}</pre><h3>Storing Data in Firebase Cloud Firestore</h3><p>Now that we’ve got authentication with Google out of the way, we’ll be sending data to Firebase in no time! But first, a little about the data structures used in Cloud Firestore.</p><h4>Cloud Firestore Data Structures</h4><p>In Firestore, everything is a Document, which are organized into Collections. A Document is basically just JSON that follows a certain structure. Collections and Documents are also created implicitly. Just write the data you want where you want and Cloud Firestore will take care of the rest! Here’s a peek at how our Firestore database will look once the root collection and its root Document are added:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*P-MpOUI0qovIrTOKNDHtkw.png" /><figcaption>Organization of Cloud Firestore database Documents into Collections</figcaption></figure><h4>Cloud Firestore Document</h4><p>So what does a Firestore Document look like? At a minimum, it must contain a name and a fields property. The fields property describes your data using JSON. Firestore also manages createTime and updateTime properties for you:</p><pre>{<br>  &quot;name&quot;: string,<br>  &quot;fields&quot;: {<br>    string: {<br>      object(Value)<br>    },<br>    ...<br>  },<br>  &quot;createTime&quot;: string,<br>  &quot;updateTime&quot;: string,<br>}</pre><p>And here’s what you have at your disposal when creating your fields object:</p><pre>{<br>  // Union field value_type can be only one of the following:<br>  &quot;nullValue&quot;: null,<br>  &quot;booleanValue&quot;: boolean,<br>  &quot;integerValue&quot;: string,<br>  &quot;doubleValue&quot;: number,<br>  &quot;timestampValue&quot;: string,<br>  &quot;stringValue&quot;: string,<br>  &quot;bytesValue&quot;: string,<br>  &quot;referenceValue&quot;: string,<br>  &quot;geoPointValue&quot;: {<br>    object(LatLng)<br>  },<br>  &quot;arrayValue&quot;: {<br>    object(ArrayValue)<br>  },<br>  &quot;mapValue&quot;: {<br>    object(MapValue)<br>  },<br>  // End of list of possible types for union field value_type.<br>}</pre><p>Feel free to reference <a href="https://firebase.google.com/docs/firestore/reference/rest/v1beta1/projects.databases.documents#Document">Firestore’s documentation</a> if you’d like to learn more about the Firestore Document model.</p><h4>Authenticating with Firestore</h4><p>In order to authenticate your requests to Cloud Firestore, simply set the value of the Authorization header to the access token obtained during the Google OAuth process:</p><pre>Authorization: Bearer {YOUR_TOKEN}</pre><p>As a side note, remember that the scope specified in the “claims” of the JWT that we created had a value of https://www.googleapis.com/auth/datastore. This scope is what tells ultimately tells Firebase that it’s okay for you to access the Firestore database.</p><h4>Accessing Firestore Data</h4><p>The Firestore REST API follows common CRUD operational patterns. CRUD is an acronym for Create Read Update Delete. The <a href="https://firebase.google.com/docs/firestore/reference/rest/#v1beta1.projects.databases.documents.METHODS_SUMMARY">Firestore documentation</a> contains details on the full list of operations available:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*ZfCPyQYTH7ZwVTmfIPt-LQ.png" /><figcaption>Cloud Firestore REST API operations</figcaption></figure><p>In order to form a Cloud Firestore request, you simply append the path to the Document in your database onto the Firestore base URL. For example, the base URL https://firestore.googleapis.com/v1beta1/ and document path /projects/YOUR_PROJECT_ID/databases/(default)/documents/cities/LA generate a final request URL that looks like this:</p><pre>https://firestore.googleapis.com/v1beta1/projects/YOUR_PROJECT_ID/databases/(default)/documents/cities/LA</pre><h4>Creating a Firestore Document</h4><p>For this example, we need to create a Document that will represent a random number. It will also include the date that the next random number will be drawn. The JSON representation for this Document will end up looking something like this:</p><pre>{<br>    &quot;name&quot;: &quot;projects/vaporfirebasedemo/databases/(databaseId)/documents/randomNumbers/theRandomNumber&quot;,<br>    &quot;fields&quot;: {<br>        &quot;number&quot;: {<br>            &quot;integerValue&quot;: 4<br>        },<br>        &quot;nextUpdate&quot;: {<br>            &quot;timestampValue&quot;: &quot;2018-02-26T16:34:46+00:00&quot;<br>        }<br>    }<br>}</pre><p>And the code that builds this:</p><pre>// Generate a new random number</pre><pre>let randomNumber = arc4random_uniform(100) + 1 // Generates a random number between [1-100]</pre><pre>// Firebase - Build the Cloud Firestore resource name</pre><pre>let projectId = &quot;vaporfirebasedemo&quot;</pre><pre>let databaseId = &quot;(default)&quot;</pre><pre>let documentPath = &quot;randomNumbers/theRandomNumber&quot;</pre><pre>let resourceName = &quot;projects/\(projectId)/databases/\(databaseId)/documents/\(documentPath)&quot;</pre><pre>// Firebase - Create a Firestore document object to represent the random number</pre><pre>var documentJSON = JSON()</pre><pre>try documentJSON.set(&quot;name&quot;, &quot;\(resourceName)&quot;) // The Firestore resource name of the document, for example projects/{projectId}/databases/{databaseId}/documents/{document_path}</pre><pre>var numberValueJSON = JSON()</pre><pre>try numberValueJSON.set(&quot;integerValue&quot;, randomNumber)</pre><pre>var numberJSON = JSON()</pre><pre>try numberJSON.set(&quot;number&quot;, numberValueJSON)</pre><pre>try documentJSON.set(&quot;fields&quot;, numberJSON)</pre><h4>Sending the Document to the Firestore Database</h4><p>First, as mentioned above, we need to form the URL that points to our Document in the Firestore database:</p><pre>let firestoreBaseURL = &quot;https://firestore.googleapis.com/v1beta1&quot;</pre><pre>let firestoreDocumentURL = &quot;\(firestoreBaseURL)/\(resourceName)&quot;</pre><p>Next, we’ll use the <a href="https://firebase.google.com/docs/firestore/reference/rest/v1beta1/projects.databases.documents/patch">patch method</a> to instruct Firebase to update or insert the Document that we send:</p><pre>// Firebase - PATCH onto the resource name to insert or update the document</pre><pre>let firestoreResponse = try self.client.patch(firestoreDocumentURL,</pre><pre>                                              query: [:],</pre><pre>                                              [.authorization: &quot;Bearer \(accessToken)&quot;],</pre><pre>                                              documentJSON,</pre><pre>                                              through: [])</pre><pre>switch firestoreResponse.status {</pre><pre>case .ok:</pre><pre>    return firestoreResponse</pre><pre>default:</pre><pre>    return Response(status: .internalServerError,</pre><pre>                    body: &quot;Error saving document to Firestore: \(firestoreResponse)&quot;)</pre><pre>}</pre><p>Finally, go ahead and make a call to your POST /nextRandom route. With any luck, you should get back the Firestore response representing the Document that was just created.</p><h3>Completed Sample Project</h3><p>Up until this point, we’ve put all of our logic inside of the Routes.swift file. However, in a production app this is highly undesirable. Feel free to check out the <a href="https://github.com/tylermilner/VaporFirebaseDemo">completed sample project on GitHub</a> to see how I organized the sample project to keep the Routes.swift file a little more lean. The completed sample also starts generating random numbers and sending them to Firestore right away. I left the implementation of the POST /nextRandom route in there, but technically it’s not necessary to call it anymore.</p><p>I’ve also posted the <a href="https://github.com/tylermilner/VaporFirebaseDemo-ClientApp">iOS client app on GitHub</a>. The client app simply observes the “randomNumbers/theRandomNumber” Document in the Firestore database. Each time a new update comes in, it displays the random number and then begins counting down the seconds until the next random number is posted based on the nextUpdate property.</p><h4>Future Improvements</h4><p>There are still some improvements that could be made to this example. One thing that you will most certainly want to take care of if you decide to use this technique in a production app is to cache the Google access token instead of performing the Google server-to-server OAuth process each time you communicate with Firebase. The access tokens you receive from Google expire after one hour so you’ll need to keep track of the expiration date of your token based on the value of the expires_in property.</p><p>Another improvement might be realized by utilizing the Firebase RPC API. From what I understand, gRPC utilizes HTTP/2 and enables realtime bidirectional streaming which could really speed things up in the communication channel between your server and Firebase. In the future, I may try to incorporate RPC as the next evolution of this demo app.</p><h3>Conclusion</h3><p>Firebase and server-side Swift are some of my favorite new tools in my toolbox as a mobile application developer. While connecting to Firebase from a server-side Swift environment isn’t quite as streamlined as connecting to Firebase from an iOS app, it’s still simple enough to do that it remains a viable option if you‘re looking to incorporate Firebase into your Swift backend.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93c11098702a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/atlas/getting-started-with-firebase-for-server-side-swift-93c11098702a">Getting Started with Firebase for Server-Side Swift</a> was originally published in <a href="https://medium.com/atlas">Atlas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[There’s a New iOS Networking Library on the Block]]></title>
            <link>https://medium.com/atlas/theres-a-new-ios-networking-library-on-the-block-dc3e3016fb61?source=rss-6a77f6e4f041------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc3e3016fb61</guid>
            <category><![CDATA[urlsessions]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[hyperspace]]></category>
            <category><![CDATA[iosnetworking]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Tyler Milner]]></dc:creator>
            <pubDate>Tue, 02 Jan 2018 15:30:05 GMT</pubDate>
            <atom:updated>2018-02-23T22:33:07.324Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*cnbPfBQ7qC6mCPBIsntaQg.png" /></figure><p>As any iOS developer knows, networking is an essential part of any mobile app. When Apple introduced URLSession in iOS 7, the community embraced it with open arms. The new APIs were a great improvement over the older URLConnection APIs. At Bottle Rocket, we’re always trying to seek a balance between efficiency and maintainability when we build apps for our clients. For this reason, we would often write our networking code from scratch, building on top of URLSession directly. This was great from a maintainability standpoint — keeping our networking code in-sync with Apple’s SDKs was extremely easy. However, as we’ve grown, we realized that there is often some common boilerplate networking code that must be written over and over again. Rather than turn to a third party solution, many of which are extremely heavy, we decided to write our own.</p><h3>Say Hello to Hyperspace</h3><p>We recently open sourced <a href="https://github.com/BottleRocketStudios/iOS-Hyperspace">Hyperspace on GitHub</a> under the Apache 2.0 license. When we built Hyperspace, we had a few goals in mind:</p><ul><li>Reduce the amount of HTTP boilerplate that you need to write by hand. This includes things like defining HTTP methods, status codes, and headers.</li><li>Keep things lightweight — make it easy and convenient to handle 90% of networking use cases out of the box. This includes specifying the model type you wish to get back from a request so that it can automatically be parsed using the magic of Swift 4’s Codable protocol.</li><li>Keep things simple — we want to make it easy for anyone to contribute. The entire library is around 600 SLOC.</li></ul><h3>Usage Example</h3><h4>Add Hyperspace to Your Project</h4><p>Once you add Hyperspace to your project, you’ll be up and running in no time. Simply add Hyperspace to your Podfile (support for other dependency managers will be added soon):</p><pre>pod &#39;Hyperspace&#39;</pre><h4>Define Network Requests</h4><p>Defining a request is simple. Simply create an instance of AnyNetworkRequest&lt;T&gt; and specify your request parameters:</p><pre>let someRequest = <br> AnyNetworkRequest&lt;Model&gt;(method: .post,<br>                          url: URL(string: &quot;...&quot;)!,<br>                          headers: [.contentType: .applicationJSON],<br>                          body: postBody)</pre><p>Notice that Model refers to the success model response type for your request. This means that if your request’s response type conforms to Decodable, we’ll automatically handle the decoding for you.</p><p>Also notice that the <em>method</em> and <em>headers</em> parameters rely on predefined types. No more “stringly typed” APIs that are prone to typos!</p><h4>Execute Network Requests</h4><p>It’s the job of a BackendService to execute your network requests. Simply create a BackendService and then call its execute() method:</p><pre>let backendService = BackendService()</pre><pre>backendService.execute(request: someRequest) { (result) in<br>    switch result {<br>    case .success(let responseObject):<br>        // Request successful<br>    case .failure(let error):<br>        // Request failed<br>    }<br>}</pre><p>Upon completion of the request, you will get back a result enum that contains your parsed Model if the request succeeded or an Error if the request failed. This is nice because you don’t have to deal with unwrapping optionals in your caller code. You also don’t have to handle “impossible” code paths like getting back a nil result object <strong>and</strong> nil error at the same time, which is one of my personal annoyances with the (Data?, URLResponse?, Error?) completion block type of URLSession’s dataTask(withRequest:completionHandler:).</p><h3>Conclusion</h3><p>I hope I’ve piqued your interest with this short article. It really is that easy to start making type-safe network requests, so if you’re looking for a networking solution in your next project, give <a href="https://github.com/BottleRocketStudios/iOS-Hyperspace">Hyperspace</a> a try. Whether you end up using it or not, we’d love for you to <a href="https://github.com/BottleRocketStudios/iOS-Hyperspace/issues/new">let us know what you think</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc3e3016fb61" width="1" height="1" alt=""><hr><p><a href="https://medium.com/atlas/theres-a-new-ios-networking-library-on-the-block-dc3e3016fb61">There’s a New iOS Networking Library on the Block</a> was originally published in <a href="https://medium.com/atlas">Atlas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Build Times in Swift 4]]></title>
            <link>https://medium.com/atlas/optimizing-build-times-in-swift-4-dc493b1cc5f5?source=rss-6a77f6e4f041------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc493b1cc5f5</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift-4]]></category>
            <category><![CDATA[compile-times]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Tyler Milner]]></dc:creator>
            <pubDate>Wed, 29 Nov 2017 17:30:52 GMT</pubDate>
            <atom:updated>2019-07-12T16:10:30.717Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*n-_AA16j7dZg6w8ybd8LxQ.png" /></figure><p>As Swift has matured, so has its compiler. We’ve come a long way since the days of the notoriously slow build times of Swift 2. Combined with the general bugginess of Xcode at the time, I’m not sure how we ever got work done back then! Although compile times seem to have gotten much better with Swift 4 and Xcode 9, are there any tweaks that we can apply to further increase performance? What about our Swift code? If you’ve followed the issue at all over the past two years, you may have run into recommendations for how to optimize your Swift code to speed up compilation times. Are those tweaks still necessary as well? In this post, I’ll do my best to answer these questions as well as provide some learnings from my own experiences with build times in Swift 4.</p><h3>Swift Build Times — Past, Present, and Future</h3><p>Though slow build times have been observed since the early days of Swift, I feel like it didn’t really become a mainstream issue until Matt Nedrich posted <a href="https://spin.atomicobject.com/2016/04/26/swift-long-compile-time/">his observations</a> about a seemingly simple code snippet that took 12+ hours to compile. Of course, the bug was fixed in Swift 3, along with improvements to compile times in projects that mixed Swift and Objective-C code. Swift 4 has continued to improve compile times, and I have no doubt that we’ll see even more improvements when Swift 5 is released next year.</p><h3>Improving Swift Build Times</h3><h4>When to Start Doing Something</h4><p>Sometimes it’s obvious that something isn’t quite right with your compile times. You may notice that your project seems to be taking forever to compile — especially if you’re switching branches often. There can also be other situations in which you may want to spend some time optimizing your build times:</p><ul><li>Midway through the project — find potential issues early as part of a mid-project “health check”</li><li>Towards the end of the project — ensure a quality initial release and set yourself up for success on future releases</li><li>Inheriting a codebase — fixing slowdowns now should pay dividends in the long run</li></ul><h3>Improving Swift Build Times</h3><h4>What Can You Do?</h4><p>There are two main things that you can do to improve your build times — adjust your project settings or adjust your Swift code. Adjusting your project settings is an easy win that can yield significant improvements and is definitely worth the time investment. Adjusting your Swift code takes more time, but can also yield positive results.</p><h3>Adjusting Project Settings</h3><h4>Build Active Architecture Only</h4><p>Make sure <strong>Build Active Architecture Only</strong> is set to <strong>Yes</strong> for <em>Debug</em> builds. This is the default when creating a new Xcode project, but it’s good to double-check to make sure it didn’t accidentally get set to something else.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*UXpbMqXcq6LoaqYX2VqGbA.png" /><figcaption>Set <strong>Build Active Architecture Only</strong> to <strong>Yes</strong> for Debug builds.</figcaption></figure><h4>Debug Information Format</h4><p>Make sure <strong>Build Options</strong> → <strong>Debug Information Format</strong> is set to <strong>DWARF</strong> for <em>Debug</em> builds. This is the Xcode default, but is good to double-check.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*Aj6HdXQT7HGeeHoi0ug9Mw.png" /><figcaption>Set <strong>Debug Information Format</strong> to <strong>DWARF</strong> for Debug builds.</figcaption></figure><p><strong>NOTE:</strong> If you’re using Fabric/Crashlytics, you may need to keep this set to <strong>DWARF with dSYM File</strong>. I started seeing console warnings from Fabric when I tried to apply this change, so I had to change it back.</p><h4>Enable Whole Module Optimization with Build Flag</h4><p>T̵h̵i̵s̵ ̵t̵w̵e̵a̵k̵ ̵i̵n̵v̵o̵l̵v̵e̵s̵ ̵e̵n̵a̵b̵l̵i̵n̵g̵ ̵W̵h̵o̵l̵e̵ ̵M̵o̵d̵u̵l̵e̵ ̵O̵p̵t̵i̵m̵i̵z̵a̵t̵i̵o̵n̵ ̵(̵W̵M̵O̵)̵ ̵f̵o̵r̵ ̵<em>D̵e̵b̵u̵g̵</em> ̵b̵u̵i̵l̵d̵s̵ ̵b̵u̵t̵ ̵t̵u̵r̵n̵i̵n̵g̵ ̵t̵h̵e̵ ̵a̵c̵t̵u̵a̵l̵ ̵o̵p̵t̵i̵m̵i̵z̵a̵t̵i̵o̵n̵ ̵p̵a̵r̵t̵ ̵o̵f̵f̵ ̵v̵i̵a̵ ̵a̵ ̵b̵u̵i̵l̵d̵ ̵f̵l̵a̵g̵.̵ ̵T̵h̵i̵s̵ ̵a̵l̵l̵o̵w̵s̵ ̵y̵o̵u̵ ̵t̵o̵ ̵s̵t̵i̵l̵l̵ ̵p̵r̵o̵p̵e̵r̵l̵y̵ ̵d̵e̵b̵u̵g̵ ̵y̵o̵u̵r̵ ̵c̵o̵d̵e̵ ̵a̵t̵ ̵r̵u̵n̵t̵i̵m̵e̵.̵</p><p>U̵n̵d̵e̵r̵ ̵<strong>S̵w̵i̵f̵t̵ ̵C̵o̵m̵p̵i̵l̵e̵r̵ ̵-̵ ̵C̵o̵d̵e̵ ̵G̵e̵n̵e̵r̵a̵t̵i̵o̵n̵</strong>,̵ ̵s̵e̵t̵ ̵t̵h̵e̵ ̵<strong>O̵p̵t̵i̵m̵i̵z̵a̵t̵i̵o̵n̵ ̵L̵e̵v̵e̵l̵</strong> ̵f̵o̵r̵ ̵<em>D̵e̵b̵u̵g̵</em> ̵t̵o̵ ̵<strong>F̵a̵s̵t̵,̵ ̵W̵h̵o̵l̵e̵ ̵M̵o̵d̵u̵l̵e̵ ̵O̵p̵t̵i̵m̵i̵z̵a̵t̵i̵o̵n̵</strong>.̵ ̵O̵n̵c̵e̵ ̵y̵o̵u̵ ̵d̵o̵ ̵t̵h̵i̵s̵,̵ ̵a̵l̵l̵ ̵o̵f̵ ̵y̵o̵u̵r̵ ̵c̵o̵n̵f̵i̵g̵u̵r̵a̵t̵i̵o̵n̵s̵ ̵w̵i̵l̵l̵ ̵l̵i̵k̵e̵l̵y̵ ̵e̵n̵d̵ ̵u̵p̵ ̵b̵e̵i̵n̵g̵ ̵s̵e̵t̵ ̵t̵o̵ ̵t̵h̵i̵s̵ ̵v̵a̵l̵u̵e̵.̵</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*7k71ly290PoGM-7HLXq_hA.png" /><figcaption>Set <strong>Optimization Level</strong> to <strong>Fast, Whole Module Optimization</strong> for Debug builds.</figcaption></figure><p>T̵h̵e̵n̵,̵ ̵u̵n̵d̵e̵r̵ ̵<strong>S̵w̵i̵f̵t̵ ̵C̵o̵m̵p̵i̵l̵e̵r̵ ̵-̵ ̵C̵u̵s̵t̵o̵m̵ ̵F̵l̵a̵g̵s̵ ̵→̵ ̵O̵t̵h̵e̵r̵ ̵S̵w̵i̵f̵t̵ ̵F̵l̵a̵g̵s̵</strong>,̵ ̵a̵d̵d̵ ̵t̵h̵e̵ ̵”̵-̵O̵n̵o̵n̵e̵”̵ ̵f̵l̵a̵g̵ ̵f̵o̵r̵ ̵t̵h̵e̵ ̵<em>D̵e̵b̵u̵g̵</em> ̵c̵o̵n̵f̵i̵g̵u̵r̵a̵t̵i̵o̵n̵.̵</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*OECYqo8u_G-mrSYar4Pq0A.png" /><figcaption>Add the <strong>-Onone</strong> flag to <strong>Other Swift Flags</strong> for Debug builds.</figcaption></figure><p>T̵h̵i̵s̵ ̵a̵l̵l̵o̵w̵s̵ ̵f̵o̵r̵ ̵t̵h̵e̵ ̵w̵h̵o̵l̵e̵ ̵m̵o̵d̵u̵l̵e̵ ̵t̵o̵ ̵b̵e̵ ̵c̵o̵m̵p̵i̵l̵e̵d̵ ̵a̵t̵ ̵o̵n̵c̵e̵ ̵w̵h̵i̵l̵e̵ ̵a̵l̵s̵o̵ ̵n̵o̵t̵ ̵p̵e̵r̵f̵o̵r̵m̵i̵n̵g̵ ̵a̵n̵y̵ ̵o̵p̵t̵i̵m̵i̵z̵a̵t̵i̵o̵n̵ ̵o̵f̵ ̵t̵h̵e̵ ̵c̵o̵d̵e̵.̵ ̵O̵n̵ ̵m̵a̵n̵y̵ ̵p̵r̵o̵j̵e̵c̵t̵s̵,̵ ̵I̵’̵v̵e̵ ̵s̵e̵e̵n̵ ̵t̵h̵i̵s̵ ̵t̵w̵e̵a̵k̵ ̵s̵p̵e̵e̵d̵ ̵u̵p̵ ̵c̵o̵m̵p̵i̵l̵e̵ ̵t̵i̵m̵e̵s̵ ̵b̵y̵ ̵a̵s̵ ̵m̵u̵c̵h̵ ̵a̵s̵ ̵2<strong>̵x</strong>̵!̵</p><p><strong><em>Update — July 2019</em></strong></p><p>At WWDC 2018, Apple highlighted this tweak as something that should no longer be necessary (both in the <a href="https://developer.apple.com/videos/play/wwdc2018/401/?time=696">What’s New in Swift</a> session and <a href="https://developer.apple.com/videos/play/wwdc2018/408/?time=1130">Building Faster with Xcode</a>). They’ve reduced the amount of redundant work being done by the compiler (something that enabling Whole Module Optimization did as a side effect). By leaving the <strong>Compilation Mode</strong> set to <strong>Incremental</strong> and <strong>Optimization Level</strong> set to <strong>No Optimization </strong>for <em>Debug</em> builds, you should have as fast, or faster builds as was possible when using this tweak. This is especially true for incremental Debug builds, since the Whole Module Optimization setting no longer causes the entire target to be rebuilt when you make small changes to files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*0O7Nw44RyVxVnq60mDvrcQ.png" /><figcaption>Optimal Swift compilation settings for <strong>Xcode 10</strong> / <strong>Swift 4.2</strong> and later.</figcaption></figure><h4>New Xcode Build System</h4><p>Xcode 9 introduced a new build system “preview” that you can opt-in to. <a href="https://www.linkedin.com/pulse/get-faster-more-stable-xcode-your-swift-projects-dan-zinngrabe/">Dan Zinngrabe</a> did some testing and found it to be 28% faster for clean builds and 82% faster for incremental builds. I personally saw a 6 second speedup in one of my projects, which was a 19% improvement for clean builds. You may also notice more responsiveness in the Xcode source editor, which is icing on the cake.</p><p>To enable the new build system, go to <strong>File</strong> → <strong>Project Settings</strong> (or <strong>Workspace Settings</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*3pnUmWA78g8vA83yXtcNHQ.png" /><figcaption>Navigate to <strong>File</strong> → <strong>Project Settings</strong>. If you’re using Cocoapods, it will be called <strong>Workspace Settings</strong> instead.</figcaption></figure><p>Change <strong>Build System</strong> to <strong>New Build System (Preview)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*O7U12JVthmnlAa4FYCISHQ.png" /><figcaption>Change the <strong>Build System</strong> to <strong>New Build System (Preview)</strong>.</figcaption></figure><p><strong><em>Update — July 2019</em></strong></p><p>As of Xcode 10, the New Build System is now the default. Some projects might still require the Legacy Build System, but you should work to get your project on the New Build System as soon as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*ViLOv62jVH-lvd4VGpit5A.png" /><figcaption>The <strong>New Build System</strong> is now the default in Xcode 10 and later.</figcaption></figure><h4>Xcode 9.2 Parallel Commands Opt-In Feature</h4><p>With the <a href="https://developer.apple.com/library/content/releasenotes/DeveloperTools/RN-Xcode/Chapters/Introduction.html#//apple_ref/doc/uid/TP40001051-CH1-SW950">release of Xcode 9.2</a>, Apple shipped an experimental opt-in feature that increases the number of concurrent build tasks that are run for Swift projects. Apple states that this may reduce build times at the expense of memory usage.</p><p>To opt-in, run the following command in Terminal:</p><pre>defaults write com.apple.dt.Xcode BuildSystemScheduleInherentlyParallelCommandsExclusively -bool NO</pre><p>To opt-out, delete the preference:</p><pre>defaults delete com.apple.dt.Xcode BuildSystemScheduleInherentlyParallelCommandsExclusively</pre><p>It’s worth noting that in my tests, I saw no difference in build times after enabling the feature, but your milage may vary.</p><h4>Reduce Dependencies</h4><p>The results from optimizations here will vary from project to project, but as a general rule of thumb, it’s good to keep project dependencies to a minimum when possible. The idea is that less code to compile == faster compile times.</p><p>New Swift features can also remove the need for some common libraries. Swift 4 saw the release of Codable, which removes the need for third party JSON parsing/serialization libraries. Next year, Swift 5 may introduce a native concurrency mechanism which could remove the need for third party promise/future/operation asynchronous libraries.</p><h3>Causes of Slow Build Times</h3><p>Per <a href="https://medium.com/swift-programming/swift-build-time-optimizations-part-2-37b0a7514cbe#ac70">Robert Gummesson</a>, there are two main causes of slow build times in Swift:</p><ul><li>An individual routine takes too long to compile — to speed things up, you can try to rewrite your code in such a way that it compiles faster</li><li>Closures and lazy properties are getting type-checked too many times, which seems to be much less of an issue in Swift 4 — I’ve not seen any code get type-checked more than once in my testing</li></ul><h3>Adjusting Your Swift Code</h3><h4>How to Know What to Adjust</h4><p>The easiest way to identify the “problem code” in your project that may be taking a long time to compile is to use the <a href="https://github.com/RobertGummesson/BuildTimeAnalyzer-for-Xcode">Swift BuildTimeAnalyzer tool</a>. Follow the setup instructions to allow the code in your project to be profiled by the tool, and then perform a clean build. Once the build is finished, you can see exactly how long each function took to compile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*HqIfYyQoHWw1lMP1YSI_Mg.png" /><figcaption>Example output from Swift <a href="https://github.com/RobertGummesson/BuildTimeAnalyzer-for-Xcode">BuildTimeAnalyzer</a> — photo credit to <a href="https://twitter.com/RobertGummesson">Robert Gummesson</a>.</figcaption></figure><h3>Common Swift “Problem Code”</h3><p>Over the past few years, many people have made public their observations about what kind of Swift code seems to give the compiler trouble. Fortunately, much of this doesn’t seem to apply anymore in Swift 4 (from my own observations, at least). If you’re curious about what has caused slowdowns in the past, feel free to check out <a href="https://gist.github.com/tylermilner/84d4f88b03c21ce6ec488e72505bec53">my Gist</a> or the “Resources” section at the end of the article.</p><h3>My “Problem Code” Observations in Swift 4</h3><p>While much of the “problem code” that seems to have plagued Swift in the past seems to no longer be an issue, I did observe some common themes that seemed to cause some minor slowdowns in Swift 4.</p><h4>Guard and FatalError</h4><p>This involved an extra guard statement that wasn’t providing much value. Before optimization, this method was taking <strong>182ms</strong> to compile:</p><pre>func item(forIndexPath indexPath: IndexPath) -&gt; SomeCellModel {</pre><pre>    let itemIndex = indexPath.row + (page * pageSize)</pre><pre>    guard itemIndex &lt; cellModels.count else {<br>        fatalError(&quot;Index out of bounds&quot;)<br>    }</pre><pre>    return cellModels[itemIndex]</pre><pre>}</pre><p>Since the system will produce a fatalError when accessing an array index out of bounds, there was no need to have the extra guard leading to a manually defined fatalError. After removing the extraneous guard, the method took <strong>91ms</strong> to compile:</p><pre>func item(forIndexPath indexPath: IndexPath) -&gt; SomeCellModel {</pre><pre>    let itemIndex = indexPath.row + (page * pageSize)</pre><pre>    return cellModels[itemIndex]</pre><pre>}</pre><h4>Complex Methods</h4><p>I saw several instances where methods that were doing several things were taking a long time to compile. One common theme was doing a lot of setup and configuration directly in viewDidLoad(). In the following example, viewDidLoad() was taking <strong>135ms</strong> to compile:</p><pre>// MARK: - Lifecycle</pre><pre>override func viewDidLoad() {</pre><pre>    super.viewDidLoad()</pre><pre>    guard let detailState = detailState else { fatalError(&quot;\(DetailState.self) not provided to \(self)&quot;) }</pre><pre>    title = detailState.navTitle</pre><pre>    navigationController?.navigationBar.titleTextAttributes = [.font: UIFont.systemFont(ofSize: 20)]</pre><pre>    navigationController?.navigationBar.tintColor = .lightGray</pre><pre>    validationController = SomeValidationController(fieldProvider: self, detailState: detailState)</pre><pre>    validationView.delegate = self</pre><pre>    setupRadioButtonView()</pre><pre>}</pre><pre>// MARK: - Private</pre><pre>private func setupRadioButtonView() {</pre><pre>    guard let detailState = detailState else { return }</pre><pre>    radioButtonView.configure(withButtonConfig: detailState.radioButtonConfig)</pre><pre>    radioButtonView.delegate = self</pre><pre>}</pre><p>It’s worth noting as well that the setupRadioButtonView() method above did not show up in the BuildTimeAnalyzer, which means that it took less than <strong>10ms</strong> to compile.</p><p>After performing some cleanup of viewDidLoad() to better adhere to the <a href="https://en.wikipedia.org/wiki/Single_responsibility_principle">single responsibility principle</a>, the method took <strong>106ms</strong> to compile.</p><pre>// MARK: - Lifecycle</pre><pre>override func viewDidLoad() {</pre><pre>    super.viewDidLoad()</pre><pre>    guard let detailState = detailState else { fatalError(&quot;\(DetailState.self) not provided to \(self)&quot;) }</pre><pre>    setupNavigationBar(withState: detailState)</pre><pre>    setupValidationController(withState: detailState)</pre><pre>    setupRadioButtonView(withState: detailState)</pre><pre>}</pre><pre>// MARK: - Private</pre><pre>private func setupNavigationBar(withState detailState: DetailState) {</pre><pre>    title = detailState.navTitle</pre><pre>    navigationController?.navigationBar.titleTextAttributes = [.font: UIFont.systemFont(ofSize: 20)]</pre><pre>    navigationController?.navigationBar.tintColor = .lightGray</pre><pre>}</pre><pre>private func setupValidationController(withState detailState: DetailState) {</pre><pre>    validationController = SomeValidationController(fieldProvider: self, detailState: detailState)</pre><pre>    validationView.delegate = self</pre><pre>}</pre><pre>private func setupRadioButtonView(withState detailState: DetailState) {</pre><pre>    radioButtonView.configure(withButtonConfig: detailState.radioButtonConfig)</pre><pre>    radioButtonView.delegate = self</pre><pre>}</pre><p>It’s worth noting the compile times of the two private methods that were created as well. The setupNavigationBar(_:) method took <strong>29ms</strong> to compile and the setupValidationController(_:) method did not register on the BuildTimeAnalyzer, so it also took less than <strong>10ms</strong> to compile. So, did we end up saving any time by splitting up viewDidLoad() into these methods? If you add up the times for all three methods, it looks like this:</p><pre>106ms + 29ms + &lt;10ms = 136-144ms</pre><p>Compared to the original compile time of <strong>135ms</strong> for viewDidLoad(), you may think that we’re actually slowing things down. However, it’s important to remember that the compilation time for a function often varies between <strong>10–20ms</strong> between runs of the BuildTimeAnalyzer. While it’s possible that everything is compiling more slowly, the reality is that the compilation times are at least as fast, if not faster after splitting up the method than they were before. You also get the added benefit of the code being more readable and better adhering to <a href="https://en.wikipedia.org/wiki/Separation_of_concerns">separation of concerns</a>.</p><h4>String Interpolation</h4><p>One thing I found interesting when analyzing my code using the BuildTimeAnalyzer was that it appears that String concatenation is no longer an area that the Swift 4 compiler struggles with. When I first encountered the code snippet below, I thought that I had hit a wall since I didn’t think there was a way to make the code compile faster:</p><pre>struct StorageConfig {</pre><pre>    let storageName: String</pre><pre>    let installationId: String</pre><pre>    var storageIdentifier: String {</pre><pre>        return &quot;\(storageName)_\(installationId)&quot;</pre><pre>    }</pre><pre>}</pre><p>The storageIdentifier property above was taking <strong>127ms</strong> to compile. Just for kicks, I decided to replace the String interpolation with String concatenation. This allowed the property to compile in <strong>60ms</strong>:</p><pre>struct StorageConfig {</pre><pre>    let storageName: String</pre><pre>    let installationId: String</pre><pre>    var storageIdentifier: String {</pre><pre>        return storageName + &quot;_&quot; + installationId</pre><pre>    }</pre><pre>}</pre><p>I’m not sure if my findings will hold true in all cases, but if you’re finding that you’d like to reduce the compilation time of some of your code that uses String interpolation, give String concatenation a try.</p><h3>Manually Optimizing Swift Code — Lessons Learned</h3><p>The Swift 4 compiler seems to be a huge step forward for reducing compilation speed bottlenecks. Here’s what I’ve learned:</p><ul><li>It’s not necessary to sacrifice Swift’s syntactic sugar and concise coding styles for faster compilation times anymore</li><li>Play around with String interpolation vs. String concatenation — interpolation might not always be faster</li><li>The Swift 4 compiler seems to be much more efficient at only type-checking things once</li><li>High compile times can be an indicator of poor separation of concerns. Use this as a guide to break apart complex functions when possible</li></ul><h3>Should You Manually Optimize Your Swift Code?</h3><p>I’ve shown you how, but <em>should</em> you put in the time to manually optimize/adjust your Swift code to speed up compile times? In general, I do<strong> not</strong> think the time saved by speeding up compilation times will be worth the time investment that’s needed to adjust or “fix” your code that’s compiling slowly. However, as mentioned above, taking the time to identify problem areas can be a good way to make improvements to how well your code adheres to the single responsibility principle and separation of concerns.</p><p>Additionally, Swift will continue to improve over time. This means that the benefits from current workarounds will diminish over time. Sacrificing conciseness and Swift syntactic sugar now will probably not be beneficial in the long run.</p><p>In my testing, I only saw a clean build speed up of about 2 seconds after fixing 23 instances of “problem code” that compiled slowly in one of my projects. In case you’re wondering, I considered anything over <strong>130ms</strong> to be something that I needed to fix (though nothing was taking over <strong>200ms</strong> to compile in the first place). This was for an unfinished project with about 10,000 lines of non-commenting, non-whitespace Swift 4 code.</p><h3>Should You Care About Swift Compile Times?</h3><p>If I don’t recommend optimizing your Swift code to improve compile times, should you even care about the compile times in your project? The short answer is <strong>YES</strong>, absolutely! Taking at least some steps to improve compile times in your project has many benefits:</p><ul><li>Spend less time compiling and more time writing code</li><li>Faster compilation times make it easier to maintain cognitive focus and “flow”</li><li>Devs that come behind you (including yourself) will thank you for not letting things get out of hand</li></ul><h3>Putting It All Together</h3><p>What steps should you take to optimize your build times in Swift 4? Here are the steps I would take to get your project building a little faster.</p><h4>Establish a Baseline</h4><p>Run the Swift BuildTimeAnalyzer to check the current status of your project. Make sure there are no obvious issues. Personally, I would consider any code that takes longer than <strong>250–500ms</strong> to compile something that should be fixed before performing more optimizations. This will of course vary based on the size of your project and your computer’s processing horsepower. In one of my projects, I saw a file take more than 11 <strong>seconds</strong> to compile. The code in question involved the JSON decoding library <a href="https://github.com/thoughtbot/Argo">Argo</a>, which I planned to replace anyway since Swift 4’s Codable is a much nicer solution.</p><h4>Manually Adjust Code (Optional)</h4><p>I’ll leave it up to you to decide if you think it’s necessary to make slight adjustments to your code to reduce the amount of time it takes to compile. At the very least, you may want to use the data to improve how well your functions adhere to the single responsibility principle.</p><h4>Adjust Your Project Settings</h4><p>If nothing else, <strong>do this</strong>! It will only take you a few minutes to make sure your project settings are optimized and can often cut your clean build times in half.</p><p>Also, give the new build system in Xcode 9 a shot. While it’s still in “preview,” it may improve your build times as well as your overall Xcode source editor experience.</p><h4>Reduce Dependencies</h4><p>In general, it’s beneficial to keep your dependencies to a minimum so that you’re not reliant on others to fix/update code when bugs are found or new versions of Xcode/Swift are released. Improvements to Swift can also negate the need for third party libraries, like the advent of Codable to replace the need for third party JSON parsing libraries.</p><h4>Future-proof Your Project</h4><p>Make sure to keep an eye on compile times as your project matures. Rather than remembering to run the BuildTimeAnalyzer every so often, consider making some final project settings tweaks to generate warnings when code takes a long time to compile.</p><p>In your project’s build settings, under <strong>Swift Compiler — Custom Flags</strong> → <strong>Other Swift Flags</strong>, add the following two flags:</p><ul><li>-Xfrontend -warn-long-function-bodies=200</li><li>-Xfrontend -warn-long-expression-type-checking=200</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*z2uJmbmOpM9IIaLeTzShzw.png" /><figcaption>Future-proofing your Xcode project to output build warnings when functions take a long time to compile.</figcaption></figure><p>The first flag — warn-long-function-bodies — has been around for a while and will report any <em>functions</em> that take longer than the threshold to type-check. The second flag — warn-long-expression-type-checking — was recently introduced in Xcode 9 and will report any <em>expressions</em> that take longer than the threshold to type-check.</p><p>Feel free to tweak the warning threshold as you see fit for your project and build system. In the example above, anything that takes longer than <strong>200ms</strong> will spit out a compiler warning when you build your project.</p><p>I̵f̵ ̵y̵o̵u̵ ̵e̵n̵a̵b̵l̵e̵ ̵t̵h̵e̵ ̵W̵h̵o̵l̵e̵ ̵M̵o̵d̵u̵l̵e̵ ̵O̵p̵t̵i̵m̵i̵z̵a̵t̵i̵o̵n̵ ̵t̵w̵e̵a̵k̵,̵ ̵y̵o̵u̵’̵l̵l̵ ̵l̵i̵k̵e̵l̵y̵ ̵w̵a̵n̵t̵ ̵t̵o̵ ̵l̵o̵w̵e̵r̵ ̵t̵h̵e̵ ̵v̵a̵l̵u̵e̵ ̵s̵i̵g̵n̵i̵f̵i̵c̵a̵n̵t̵l̵y̵ ̵a̵s̵ ̵w̵e̵l̵l̵ ̵s̵i̵n̵c̵e̵ ̵e̵v̵e̵r̵y̵t̵h̵i̵n̵g̵ ̵w̵i̵l̵l̵ ̵c̵o̵m̵p̵i̵l̵e̵ ̵m̵u̵c̵h̵ ̵f̵a̵s̵t̵e̵r̵.̵ ̵I̵’̵d̵ ̵r̵e̵c̵o̵m̵m̵e̵n̵d̵ ̵s̵t̵a̵r̵t̵i̵n̵g̵ ̵a̵t̵ ̵a̵ ̵<strong>1̵0̵0̵m̵s̵</strong> ̵t̵h̵r̵e̵s̵h̵o̵l̵d̵ ̵a̵f̵t̵e̵r̵ ̵e̵n̵a̵b̵l̵i̵n̵g̵ ̵t̵h̵e̵ ̵W̵M̵O̵ ̵t̵w̵e̵a̵k̵.̵</p><p><strong><em>Update — July 2019</em></strong></p><p>As mentioned above, the Whole Module Optimization tweak should no longer be necessary and is no longer recommended.</p><p>An additional tweak you can apply to keep an eye on build times is to enable the build duration to be shown as part of the build status window in the center-top of Xcode by running the following command in Terminal:</p><pre>defaults write com.apple.dt.Xcode ShowBuildOperationDuration -bool YES</pre><p>Restart Xcode if it was already running and then perform a build. You’ll see the build duration is now shown next to the build status at the top of Xcode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*-Xww4047qtNRPQpp7IcBYw.png" /><figcaption>Enabling the build duration to be shown next to the build status.</figcaption></figure><h3>Conclusion</h3><p>I hope you found the information here useful. Overall, it seems that things are getting much better in terms of Swift compilation times, but there are still some small tweaks that can provide significant speedups in your project’s compilation times. I spent several hours researching this topic and gathering information and have listed my resources in the section below. Feel free to look them over and let me know if there’s anything I missed or if you have any of your own tips and tricks to speed things up. Personally, I was able to reduce build times from <strong>61s</strong> to <strong>26s</strong> (57% speedup) in one of my projects and <strong>64s</strong> to <strong>23s</strong> (64% speedup) in another project. At the end of it all, I hope you’ll take a few minutes to optimize your projects so that you can quit slacking off! 😉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*eGP2-gNYhN6e1ZH8W64utA.png" /><figcaption>The classic “my code’s compiling” programmer excuse via <a href="https://xkcd.com/303/">xkcd</a>.</figcaption></figure><h3>Resources</h3><ul><li><a href="http://irace.me/swift-profiling">Profiling your Swift compilation times</a></li><li><a href="https://spin.atomicobject.com/2016/04/26/swift-long-compile-time/">Go Home Swift Compiler, You’re Drunk</a></li><li><a href="https://medium.com/@RobertGummesson/regarding-swift-build-time-optimizations-fc92cdd91e31">Regarding Swift build time optimizations</a></li><li><a href="https://medium.com/swift-programming/swift-build-time-optimizations-part-2-37b0a7514cbe">Swift build time optimizations — Part 2</a></li><li><a href="https://littlebitesofcocoa.com/235-debugging-slow-builds-with-buildtimeanalyzer">#235: Debugging Slow Builds with BuildTimeAnalyzer</a></li><li><a href="http://roadfiresoftware.com/2017/01/improving-swift-compile-times/">Improving Swift Compile Times</a></li><li><a href="https://www.prolificinteractive.com/2017/05/30/exploring-swift-build-times/">Exploring Swift Build Times</a></li><li><a href="https://hackernoon.com/speed-up-swift-compile-time-6f62d86f85e6">Speed up Swift compile time</a></li><li><a href="https://www.hackingwithswift.com/articles/11/how-to-make-swift-compile-faster">How to make Swift compile faster</a></li><li><a href="https://medium.com/@johnsundell/improving-swift-compile-times-ee1d52fb9bd">Improving Swift compile times</a></li><li><a href="https://www.jessesquires.com/blog/measuring-compile-times-xcode9/">Measuring Swift compile times in Xcode 9</a></li><li><a href="https://github.com/fastred/Optimizing-Swift-Build-Times">Optimizing Swift build times</a></li><li><a href="https://www.linkedin.com/pulse/get-faster-more-stable-xcode-your-swift-projects-dan-zinngrabe/">Get a faster, more stable Xcode for your Swift projects</a></li><li><a href="http://developear.com/blog/2016/12/30/Speed-Swift-Compilation.html">Speeding Up Compile Times of Swift Projects</a></li><li><a href="https://tonyarnold.com/2016/04/20/xcode-build-duration.html">How to show the duration of builds in Xcode</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2018/401/">WWDC 2018 — What’s New in Swift</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2018/408/">WWDC 2018 — Building Faster in Xcode</a></li></ul><h3><strong><em>Update — July 2019</em></strong></h3><p>At WWDC 2018, Apple provided many good build speedup tips in the <a href="https://developer.apple.com/videos/play/wwdc2018/408/">Building Faster in Xcode session</a>. I’ve summarized some of the information below, but you should make sure to check out the video for all the details!</p><h4>Parallelize Build</h4><p>Make sure your scheme has the “Parallelize Build” option checked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*raAzVH7usDyXoka7YcW8og.png" /><figcaption>Enable the <strong>Parallelize Build</strong> option in your project’s scheme.</figcaption></figure><h4>Examine and Optimize Dependencies</h4><p>You should watch the WWDC video to get all the details, but essentially the main ideas are to make sure the dependency hierarchy is optimized for the targets in your app (e.g. if a target needs just a small section of a dependency, consider breaking it off into its own module). Also, make sure to routinely cleanup unused dependencies (much in the same way you want to periodically cleanup dead code).</p><h4>Reduce the Amount of Rebuild Work for Run Script Phases</h4><p>Populate the “Input Files” parameter for your run script with the files your script will read or use during the script execution. This will help Xcode determine if your run script phase should actually run or not. New in Xcode 10, you can also provide this information as an xcfilelist via the “Input File Lists” parameter. Likewise, populating the “Output Files” (or “Output File Lists”) parameter will also help Xcode determine if the run script phase should be executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UImslMMzBGaK1M0J_fmAJA.png" /><figcaption>Populate <strong>Input Files</strong> and <strong>Output Files</strong> parameters to help Xcode determine if the run script phase should be run or not.</figcaption></figure><p>Xcode uses the following logic to determine if your run script phase should be run:</p><ul><li>No input files declared (i.e. Xcode will run the script for every build)</li><li>Input files changed</li><li>Output files are missing</li></ul><p>This information is also now documented in the <a href="https://help.apple.com/xcode/mac/11.0/index.html?localePath=en.lproj#/devc8c930575">Run a shell script section</a> of the Xcode Help.</p><h4>Measuring Build Time</h4><p>Xcode 10 now includes in-line task timings in the build log so that you can see how long each build task takes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nmsygfd0mptC7hrMFDdolg.png" /><figcaption>Xcode 10 build task timings in the build log.</figcaption></figure><p>You can also have Xcode generate a timing summary section at the end of the build log to get an aggregate timing of all of the tasks that went into the build operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*QomwAcxupi3FDg1unWo2IA.png" /><figcaption><strong>Select Product</strong> → <strong>Perform Action</strong> → <strong>Build with Timing Summary</strong> to have Xcode generate a <strong>Build Timing Summary</strong> section at the end of the build log.</figcaption></figure><p>Using the timing summary, you can check to make sure your run script phases are configured properly. If you see “PhaseScriptExecution” eating up time on every build (especially incremental builds), then it’s a good indicator that something isn’t configured properly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*hSnlGt9IZZU7ZexMclbs3g.png" /><figcaption>Keep an eye on the amount of time being spent on <strong>PhaseScriptExecution</strong> during incremental builds.</figcaption></figure><h4>Dealing with Complex Expressions</h4><p>Although not as commonly necessary as in previous versions of Swift, sometimes explicitly providing type information can help speed up compilation.</p><p><strong>Use Explicit Types for Complex Properties</strong></p><p>For complex computed properties, explicitly providing type information can help keep the Swift compiler from having to spend extra time inferring the type. This also helps to improve readability, since the reader doesn’t need to spend time trying to figure out the type either.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VxTelSfTPzgAy14ejnT-tA.png" /><figcaption>Provide explicit type information for complex properties when necessary.</figcaption></figure><p><strong>Provide Types in Complex Closures</strong></p><p>Similar to the above, providing explicit type information for closures can help save the compiler some work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CYHjr1hLCW_2VD7z1UFMqA.png" /><figcaption>Provide explicit type information for closures.</figcaption></figure><p><strong>Break Apart Complex Expressions</strong></p><p>Breaking up a complex expressions into separate statements can improve readability and improve compilation times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2lFEjUTWHa_fRThdqSbz6w.png" /><figcaption>Break up complex single-line statements into multiple lines.</figcaption></figure><p><strong>Use </strong><strong>AnyObject Methods and Properties Sparingly</strong></p><p>Using the AnyObject type inherits some features of the id type from Objective-C. Because the type is not known, the Swift compiler must assume that any methods in the project marked as @objc can potentially be called. This means that the compiler must look across the entire project to make sure you’re calling a valid implementation. Instead of declaring conformance to AnyObject, it’s better to define and use a protocol for things like delegate types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YbyMJstx5dpuAXlw_5EQGQ.png" /><figcaption>Define and use a <strong>protocol</strong> rather than <strong>AnyObject</strong>.</figcaption></figure><h4>Understanding Dependencies in Swift</h4><p>Understanding how Swift determines which files need to be recompiled can help you make sure you’re not introducing additional overhead during compilation time.</p><p><strong>Incremental Builds are File-Based</strong></p><p>For incremental builds, the Swift compiler determines what needs to be recompiled based on file changes. Adding/removing types from a file or changing a type’s interface will trigger a rebuild of that file and whatever files depend on it (including files in other targets). However, changing the implementation details of a <em>function</em> won’t cause dependent code to be recompiled. Although Apple didn’t explicitly state it, I would infer this to be a good reason why you should prefer splitting up types into several small files rather than declaring many types in a single file.</p><h4>Limiting Your Obj-C/Swift Interface</h4><p>As you probably know, the Obj-C bridging header defines the Obj-C code that’s exposed to Swift. Likewise, the Swift generated header defines the Swift code that’s exposed to Obj-C. The main idea here is to shrink the amount of content in these headers so that are fewer chances for things to change and decrease the need for files to be recompiled.</p><p><strong>Use </strong><strong>private when Possible</strong></p><p>Using private in your Swift code will prevent methods from being exposed to Obj-C via the generated header. This includes @IBOutlet and @IBAction declarations, so making sure to declare these as private can help reduce the amount of code that winds up in the Swift generated header.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n0VhOIlLJWTOLZbZf0_SCA.png" /><figcaption>Make <strong>@IBOutlet</strong> properties and <strong>@IBAction</strong> methods <strong>private.</strong></figcaption></figure><p>Another example is methods that need to be exposed to Obj-C for use with Obj-C runtime features, like NotificationCenter’s requirement to provide a #selector as a parameter when adding observers. Either marking the method referenced by the #selector as private or switching to block-based APIs can help ensure the method doesn’t make it into the Swift generated header.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GLsgQmFXt1pBVgN1Jy3zXA.png" /><figcaption>Make methods used with <strong>NotificationCenter</strong> observers <strong>private</strong>.</figcaption></figure><p><strong>Migrate to Swift 4</strong></p><p>Migrating from Swift 3 to Swift 4 preserves @objc inference by default. This means that methods and properties on any subclass of NSObject are exposed to Obj-C. Make sure to finish your migration to Swift 4 by removing the override on the <strong>Swift 3 @objc Inference</strong> build setting (to set it to <strong>Default</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ul-cZc2dZjT2JcDhVnAMyA.png" /><figcaption>Set the <strong>Swift 3 @objc Inference</strong> build setting to <strong>Default</strong>.</figcaption></figure><p><strong>Keep Your Bridging Header Minimal</strong></p><p>For the Obj-C interface files (.h) declared in the bridging header, audit the properties and methods declared on each of those classes to make sure they’re actually used by Swift. It’s possible many of these can be moved inside of the implementation file (.m) to make them private and prevent them from being included as part of the Obj-C bridging header.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PKwtmjX_780sYOE8LP4Oig.png" /><figcaption>Make sure Obj-C header files included in the bridging header only contain methods and properties that need to be used in Swift.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc493b1cc5f5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/atlas/optimizing-build-times-in-swift-4-dc493b1cc5f5">Optimizing Build Times in Swift 4</a> was originally published in <a href="https://medium.com/atlas">Atlas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step Up Your Functional Game — Map and FlatMap Tricks]]></title>
            <link>https://medium.com/atlas/step-up-your-functional-game-map-and-flatmap-tricks-cdc1578fe7bc?source=rss-6a77f6e4f041------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdc1578fe7bc</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Tyler Milner]]></dc:creator>
            <pubDate>Wed, 25 Oct 2017 16:12:32 GMT</pubDate>
            <atom:updated>2018-02-23T22:34:21.672Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*1TpfVQ03gL8PxMX5LKHuRg.png" /></figure><p>Swift has been out for more than three years now, and as I’ve learned the language, I’ve tried to incorporate more functional programming techniques into my code. Coming from an extensive background in Objective-C, I’ll admit that I really didn’t understand <em>map</em> and <em>flatMap</em> when first learning Swift. Eventually, I was comfortable enough with the concepts to start using them to replace some of my for loops. Until recently, that’s all I really considered <em>map</em> and <em>flatMap</em> to be useful for. It wasn’t until I attended <a href="https://twitter.com/teamneem">Neem Serra</a>’s Map and FlatMap Magic talk at try! Swift NYC 2017 that my eyes were opened to a world of other great uses for <em>map</em> and <em>flatMap</em>. Much of the content in this post is based on Neem’s presentation, so make sure to check out <a href="https://academy.realm.io/posts/try-swift-nyc-2017-neem-serra-map-and-flatmap-in-swift/">her talk on Realm Academy</a> when you get a chance!</p><h3>Map</h3><p>The most basic definition I could come up with for <em>map</em> is that it transforms data into a different type. Typically, it’s used to loop over a collection and transform each element so you can do things like create an array of Strings from an array of Ints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*YboK8kC64bziOAs_Mw2BqA.png" /><figcaption><a href="https://developer.apple.com/documentation/swift/array/2908681-map">Apple’s documentation</a> for map on the Array type.</figcaption></figure><h3>FlatMap</h3><p>Like <em>map</em>, <em>flatMap</em> transforms data into a different type. <em>FlatMap</em> also has a special property of “removing a layer.” One example is removing a layer of nesting, where a 2-dimensional array is “flattened” into a 1-dimensional array. Another example is removing nil elements from an array that’s populated with optionals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*2kcokp9I3kJL16WtFB2dGg.png" /><figcaption><a href="https://developer.apple.com/documentation/swift/sequence/2905332-flatmap">Apple’s documentation</a> for <em>flatMap</em> on the Sequence type.</figcaption></figure><h3>Map and FlatMap Basics</h3><h4>Setup</h4><p>As in Neem’s talk, I’m going to showcase <em>map</em> and <em>flatMap</em> techniques using cupcakes. Here’s the model we’ll be working with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*LekpvnjH-wrXKphi67ld4A.png" /><figcaption>Cupcake model — a simple struct.</figcaption></figure><p>As you can see, the model is dead simple. A Cupcake has a flavor property and there is one method to retrieve that flavor. In reality, there’s no need for the getFlavor() method since we could just access the flavor property directly. But for our example, we’ll leave it as is.</p><p>Up next, we’ll create some Cupcakes and stick them in a cupcakes array:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*MTsi3eN8PeTQzY3BVOqlfw.png" /><figcaption>Creating an array of Cupcakes.</figcaption></figure><p>The rest of the examples will use this basic setup to illustrate different <em>map</em> and <em>flatMap</em> techniques. A playground is also provided at the end of the article.</p><h4>Map — The Old Way</h4><p>Does this code look familiar? I know I was guilty of writing code in this style when first learning Swift. Here, we’re transforming and array of Cupcakes into an array of Strings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*U-YqWsljooFDdChXr5YGjw.png" /><figcaption>The old way — Transforming [Cupcake] into [String] using <strong>for</strong>.</figcaption></figure><h4>Map — The New Way</h4><p>Using <em>map</em>, we can reduce the 4 lines of code above into a single line. Neat!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*GEQzI7wKoU3VBhTXJA-pNg.png" /><figcaption>The new way — Transforming [Cupcake] into [String] using <strong>map</strong>.</figcaption></figure><h4>Map — The Wrong Way</h4><p>You should really only use <em>map</em> to <strong>transform</strong> elements. While it’s technically possible to <strong>generate</strong> elements using <em>map</em>, you should avoid the urge to do so, if possible. A good rule of thumb is to watch for ignoring the closure parameter. If you’re writing something like .map { _ in ... } (note the <strong>underscore</strong>), then you’re probably <strong>not</strong> using <em>map</em> correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*oKWRkr3Osgg3mW8F0ZXkoA.png" /><figcaption>The wrong way— Using <strong>map</strong> to generate elements rather than transform them.</figcaption></figure><h4>Mapping with Optionals</h4><p><em>Map</em> can also be used on optionals. For reference, let’s look at how optionals normally behave when you try to use them without first unwrapping them. You’ll most definitely see a compiler error complaining about the optional not being unwrapped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1THsv_5Lrk8rkJ5D--DGvg.png" /><figcaption>Compiler error when trying to use an optional without unwrapping it first.</figcaption></figure><p>You can use <em>map</em> to work around this, using it to unwrap the optional, if it exists, and give you a chance to work with the value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*EVUn0EZVCg8kc_GJ4hulRQ.png" /><figcaption>The closure passed to <strong>map</strong> will only be executed if the value for the optional exists.</figcaption></figure><p>It’s important to note that the type of the newCount variable above remains an Int? or Optional&lt;Int&gt;. An easy way to think about it is when you pass an optional to <em>map</em>, <em>map</em> will unwrap it and let you do something with the value inside of the closure. <em>Map</em> will then re-wrap it as an optional and return it to you.</p><h4>FlatMap — The Old Way</h4><p>When dealing with nested, or multi-dimensional arrays, our code would often look something like this when we needed to reduce it down to a single-dimensional array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*F0gg6xDIQGpomyR1F_FHQg.png" /><figcaption>Using a <strong>for</strong> loop to convert [[Cupcake]] into [Cupcake].</figcaption></figure><h4>FlatMap — The New Way</h4><p>Because of <em>flatMap</em>’s ability to “remove a layer,” we can perform the same operation in one line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*cQ3rEdfmk5elz20y4oyn4A.png" /><figcaption><strong>FlatMap</strong> converts [[Cupcake]] into [Cupcake].</figcaption></figure><h4>FlatMapping with Optionals</h4><p>Like <em>map</em>, <em>flatMap</em> can also be used with optionals. When you pass an optional in to <em>flatMap</em>, <em>flatMap</em> will unwrap the optional if it exists, giving you a chance to do something with the value, or return nil. A neat trick is using the <em>nil-coalescing</em> operator to then provide a default value in case the unwrapping fails.</p><p>Let’s say on some days there is a “featured cupcake,” which becomes the flavor of the day. Whenever there is no “featured cupcake,” we’ll say that vanilla is going to be the default flavor of the day. We can model this scenario in a single line using <em>flatMap</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_rF_TmSOrgNsRMV2u-nTQ.png" /><figcaption>Using <strong>flatMap</strong> with the <strong>nil-coalescing</strong> operator allows you to unwrap an optional and provide a default value.</figcaption></figure><p>Note that the type of flavorOfTheDay is <strong>not</strong> an optional. Since we’re using the <em>nil-coalescing</em> operator to provide a default value, flavorOfTheDay is simply a String.</p><h3>Map Tricks</h3><h4>Add Optional Subview — The Old Way</h4><p>UIView’s addSubview(…) method takes a non-optional UIView so you would usually find yourself having to unwrap the optional view first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*ai8WlkjSzlayOk52FX02fw.png" /><figcaption>The old way — using <strong>if let</strong> to unwrap the optional first.</figcaption></figure><h4>Add Optional Subview — The New Way</h4><p>Since <em>map</em> only runs its closure if the optional value exists, we can simplify the above code down to one line. No more if let for this simple operation!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*wuROkTJmP5r2UgX3Ty7U4Q.png" /><figcaption>The new way — using <strong>map</strong> to unwrap and add the subview.</figcaption></figure><h4>String Interpolation — The Old Way</h4><p>Let’s say we’re needing to display the number of cupcakes to the user. If the numberOfCupcakes variable is nil, we want to display the text “Unknown number.” Otherwise, we need to generate a String describing how many cupcakes are in the box. Without <em>map</em>, we may have done it like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JBcvjUtKvAzxh1KJ0lufDw.png" /><figcaption>Using <strong>var</strong> and <strong>if let</strong> to generate a String based on the value of an optional.</figcaption></figure><p>You may be familiar with the <em>ternary operator</em>. Maybe we could use it to simplify things.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QHc2PY4juRStokFd9s6xrw.png" /><figcaption>Using the <strong>ternary operator</strong> to generate a String based on the value of an optional.</figcaption></figure><p>Unfortunately, the use of the <em>ternary operator</em> breaks our requirements. When numberOfCupcakes is not nil, there will be undesirable output because the full description of the optional will be used instead of its value (Optional(0) instead of 0).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X9ULl4Dx2Fv2f2zP50mimA.png" /><figcaption>Output from <strong>ternary operator</strong> use yields undesirable <strong>Optional(0)</strong> text.</figcaption></figure><p>The <em>nil-coalescing</em> operator can be used to fix. By adding ?? 0, it allows the value of numberOfCupcakes to be automatically unwrapped, falling back to the default value of 0 if the unwrapping fails. However, this is a bit ugly. Because the <em>ternary operator</em> will cause the code to short circuit to “Unknown number” when numberOfCupcakes is nil, the code path created with the <em>nil-coalescing</em> operator will never be executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BjEs-BMAuU9NMz-3HONteg.png" /><figcaption>Using the <strong>nil-coalescing</strong> operator to provide a default value to the optional unwrapping.</figcaption></figure><h4>String Interpolation — The New Way</h4><p>Using <em>map</em>, in combination with the <em>nil-coalescing</em> operator, we can adhere to our requirements while avoiding the creation of “unrunnable” code paths.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qjmN96h7FFcluHt68mCi0A.png" /><figcaption>Using <strong>map</strong> and the <strong>nil-coalescing</strong> operator to generate a String based on the value of an optional.</figcaption></figure><h4>Shortcut on Init — The Old Way</h4><p>As we’ve seen before, we can use <em>map</em> to transform elements in an array into a different type. Using the shorthand notation, the implicit $0 parameter can be passed into the initializer of the desired type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*IooN-3El-o823eWs9LHY3A.png" /><figcaption>The old way — using <strong>map</strong> closure with implicit $0 parameter.</figcaption></figure><h4>Shortcut on Init — The New Way</h4><p>Since functions are <em>first-class citizens</em> in Swift, we can pass the init function directly to <em>map</em> as a parameter and avoid writing a closure at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*G42--Q10GSUXWYCmhm3wCg.png" /><figcaption>The new way — passing an init function into <strong>map</strong> directly — no closure needed.</figcaption></figure><p>I’m still on the fence about adopting this technique throughout my code. On one hand, it’s kind of a nice simplification to how you call <em>map</em>. On the other hand, it can’t be used in every situation so it would create minor inconsistencies in your usage of <em>map</em> throughout your codebase.</p><h3>FlatMap Tricks</h3><h4>Filter Objects That Fail on Init — The Old Way</h4><p>Here’s another snippet of code that probably looks familiar if you come from an Objective-C background like myself. We have some identifiers that represent images that need to be loaded from the bundle into an array. Since UIImage’s image(named:) initializer is <em>failable</em>, we need to use an if let when creating the images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*MuQ72t4YNdaofDH_llptDw.png" /><figcaption>The old way — using <strong>if let</strong> to unwrap the result of a failable initializer.</figcaption></figure><h4>Filter Objects That Fail on Init — The New Way</h4><p>Let’s look at what happens when we use <em>map</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*GLyN03vdrpbEa9twzk7z8Q.png" /><figcaption>The new way — using <strong>map</strong> with a failable initializer.</figcaption></figure><p>Since <em>map</em> attempts to unwrap an optional and then rewrap it, we actually get back an array of optional images — [UIImage?]. Not quite what we want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i0U20T80L_D_SkWtDst2Hw.png" /><figcaption>Result of using <strong>map</strong> with a failable initializer — an array of optionals.</figcaption></figure><p>Because <em>flatMap</em> removes a layer, it will return the value of the optional, if it exists, or nil. This means the images array is of type[UIImage]. Whenever the initializer fails, nothing will be added to the array instead of an Optional&lt;UIImage&gt; with a nil value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*nzqjum8CRNP9krcx0M49JQ.png" /><figcaption>The new way — using <strong>flatMap</strong> with a failable initializer.</figcaption></figure><p>In the attached playground, the array is empty because there are not actually any image resources included.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*sgWEEjndkNpdbwMnA70y7w.png" /><figcaption>Result of using <strong>flatMap</strong> with a failable initializer — an empty array if the initializer failed for all elements.</figcaption></figure><h4>Get Data for Onscreen Cell — The Old Way</h4><p>Sometimes you need to get the data associated with a cell that’s shown in a table or collection view and doesn’t have a direct reference to the corresponding IndexPath. Typically, you would use if let to unwrap an IndexPath using UITableView’s indexPath(for:) method. Once you have the index of the cell, you typically use the row property as the index for your data array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ox0v8rOyzqpuR94zm41kRQ.png" /><figcaption>The old way — using <strong>if let</strong> to get the IndexPath for a table view’s cell.</figcaption></figure><h4>Get Data for Onscreen Cell — The New Way</h4><p><em>FlatMap’s</em> property of transforming an optional, if it exists, or returning nil can provide an alternative implementation. If the indexPath(for:) method returns a valid IndexPath, we can use it to access the corresponding piece of data inside of the <em>flatMap</em> closure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OApMI06we5Bc6QN0osQJxw.png" /><figcaption>The new way — using <strong>flatMap</strong> to transform an optional IndexPath into the corresponding cell data.</figcaption></figure><h3>Why Use Map and FlatMap?</h3><h4>Be Functional</h4><p>Functional programming is cool, and we’ve only recently been able to take advantage of this tool thanks to the release of Swift.</p><p>One great aspect of functional programming is the ability to avoid mutable state. Not only can this help avoid potential bugs, but I think it also reads better, requiring less overall cognitive overhead.</p><p>When you see something is let, you know immediately that the value of that variable will not change for the rest of its scope. When it comes time to actually define the value of the variable, I find that transforming an optional using <em>flatMap</em> then using the <em>nil-coalescing</em> operator to define a default value reads very well. To me, a single line is easier and quicker to understand than having to track the value of a variable through several lines of an if/else block.</p><h4>Visually Explicit Chaining</h4><p>Visually Explicit Chaining refers to the ability to chain together several map and flatMap operations to define a stream of sequential changes that transform data over time.</p><p>Borrowing a slide from <a href="https://academy.realm.io/posts/try-swift-nyc-2017-neem-serra-map-and-flatmap-in-swift/">Neem’s presentation</a>, the instructions are to combine boxes, remove nil cupcakes, frost the cupcakes, and then add sprinkles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*X9V7wF3hTIZ-wlZV6HPycA.png" /><figcaption>Using <strong>visually explicit chaining</strong> to apply transformations in a sequential, easy to follow manner — photo credit to <a href="http://twitter.com/teamneem">Neem Serra</a>.</figcaption></figure><p>The result is an array of sprinkled Cupcakes. If you’re reading closely, you may have also noticed that the print(cupcakes) statement should actually be print(deliciousness). 😉</p><h3>Conclusion</h3><p>A <a href="https://gist.github.com/tylermilner/01043e40cde9734dd1aec91d5da2cb8d">Swift playground</a> is available as a GitHub Gist that contains all of the examples shown here. It was written in Swift 4 / Xcode 9.</p><p><em>Map</em> and <em>flatMap</em> have many more use cases beyond the obvious one of transforming arrays into different types. I hope I’ve introduced you to at least one cool new trick that you may start adopting in your Swift code. Do you know of any other great uses for <em>map</em> and <em>flatMap</em>? If so, feel free to drop a comment and help us <strong>all</strong> step up our functional game!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdc1578fe7bc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/atlas/step-up-your-functional-game-map-and-flatmap-tricks-cdc1578fe7bc">Step Up Your Functional Game — Map and FlatMap Tricks</a> was originally published in <a href="https://medium.com/atlas">Atlas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[try! Swift NYC 2017 Recap]]></title>
            <link>https://medium.com/atlas/try-swift-nyc-2017-recap-5ad479179a1f?source=rss-6a77f6e4f041------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ad479179a1f</guid>
            <category><![CDATA[try-swift]]></category>
            <category><![CDATA[ios-11]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Tyler Milner]]></dc:creator>
            <pubDate>Mon, 25 Sep 2017 13:47:59 GMT</pubDate>
            <atom:updated>2018-02-23T22:34:57.950Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*VraYdw7COLJdoAlvmt6bFQ.png" /></figure><p>In case you’ve never heard of it, try! Swift is one of the newest iOS conferences on the block. First starting in Japan in March of 2016, try! Swift has quickly become an international conference, recently adding <a href="https://www.tryswift.co/events/2017/bangalore/">Bangalore</a> as its third and final stop for this year. The conference is organized by Natasha Murashev (<a href="https://twitter.com/NatashaTheRobot"><strong>@</strong>NatashaTheRobot</a>) who also runs the <a href="https://swiftnews.curated.co/">This Week in Swift</a> iOS newsletter (which I <em>highly</em> recommend signing up for). Earlier this month, I had the opportunity to attend my first try! Swift conference in New York City.</p><h3>About the Conference</h3><p>The single track conference spanned three days — one pre-conference workshop + two main conference days — and had some awesome presentations by over 20 speakers. I really enjoyed the format of the conference, with each talk lasting roughly 20–30 min and direct access to the speakers during “office hours.” There was a dedicated space outside of the main theater where each speaker would post up for questions immediately after his or her talk.</p><p>In addition to all of the wonderful speakers, there were what I consider some “big names” in the iOS community in attendance as well. There was support from server-side swift leaders like <a href="https://twitter.com/iamjono">Jonathan Guthrie</a> (<a href="http://perfect.org/">Swift Perfect</a>), who ran the server-side Swift workshop; and <a href="https://twitter.com/tanner0101">Tanner Nelson</a> (<a href="https://vapor.codes/">Vapor</a>), who did a presentation on server-side Swift and Vapor in general. <a href="https://github.com/ReactiveX/RxSwift">RxSwift</a> founder, <a href="https://twitter.com/krunoslavzaher">Krunoslav Zaher</a>, did a talk on a new RxSwift architecture called <a href="https://github.com/kzaher/RxFeedback">RxFeedback</a>. There were also well-established bloggers like <a href="https://twitter.com/khanlou">Soroush Khanlou</a> (<a href="http://khanlou.com/">khanlou.com</a>), who wasn’t a schedule speaker, but filled in for a presenter who got sick. Other blogging veterans include <a href="https://twitter.com/cocoawithlove">Matt Gallagher</a> (<a href="https://www.cocoawithlove.com/">cocoawithlove.com</a>), who did a great view-state driven application presentation; and <a href="https://twitter.com/ashfurrow">Ash Furrow</a> (<a href="https://ashfurrow.com/">ashfurrow.com</a>), who ran the RxSwift workshop.</p><h3>Favorite Talks</h3><p>These are my notes from some of my favorite talks of the conference. While <a href="https://www.tryswift.co/events/2017/nyc/#schedule">all of the talks</a> were awesome, these presentations stood out as being most relevant to my current proficiency and interests within iOS development. I’ve included links to code and/or presenter notes, if possible. I will do my best to keep the page updated as I find more speaker materials are released. It’s also worth noting that all talks were recorded by <a href="https://realm.io/">Realm</a>, and the videos/transcripts will be available soon!</p><p><strong>Update 9/26/2017:</strong> Realm has started posting the videos from try! Swift NYC 2017. Check them out on the <a href="https://academy.realm.io/conferences/try-swift-nyc-2017/">conference page of Realm Academy</a>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/94/1*B1dp-3rxYde_BP0RY2k4NA.png" /></figure><h4>Map and FlatMap Magic</h4><p><a href="http://twitter.com/teamneem"><strong>Neem Serra</strong></a></p><p><strong>Video:</strong> <a href="https://academy.realm.io/posts/try-swift-nyc-2017-neem-serra-map-and-flatmap-in-swift/">https://academy.realm.io/posts/try-swift-nyc-2017-neem-serra-map-and-flatmap-in-swift/</a></p><p><strong>Slides:</strong> <a href="http://slideshare.net/NeemSerra/map-and-flat-map-magic">slideshare.net/NeemSerra/map-and-flat-map-magic</a></p><p>This talk contained many cool and new (to me) map and flatMap techniques. Neem went over the basics of map and flatMap using example collections of simple Cupcake structs to make it easier to understand what was going on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*j-_VP_QMMJMYg5QQ1t2hxg.png" /><figcaption>photo credit to <a href="http://twitter.com/teamneem">Neem Serra</a></figcaption></figure><p>I really enjoyed how Neem gave several before and after examples where she showed the “old way” of doing something before unveiling the “new way” of accomplishing the same task using functional techniques.</p><p>The “old way” typically involves a lot of for loops that modify mutable state. This is one of the shorter examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*dT5JvXkfy2XfM5nMgzn6pA.png" /><figcaption>The “old way” — mutable state — photo credit to <a href="http://twitter.com/teamneem">Neem Serra</a></figcaption></figure><p>The new, functional way of doing things involves what Neem described as “visually explicit chaining” to create a clear, sequential code path:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*8RGJHFtAU6ACxtz4O55mzA.png" /><figcaption>The “new way” —functional/“visually explicit chaining” — photo credit to <a href="http://twitter.com/teamneem">Neem Serra</a></figcaption></figure><p>Despite the somewhat introductory sounding title, there was so much good information in this presentation that I will be doing a separate blog post later to highlight the tips and tricks I felt will help me the most!</p><h4>Driving view state through data for fun and/or debugging</h4><p><a href="https://twitter.com/cocoawithlove"><strong>Matt Gallagher</strong></a></p><p><strong>Video:</strong> <a href="https://academy.realm.io/posts/try-swift-nyc-2017-matt-gallagher-driving-view-state-through-data/">https://academy.realm.io/posts/try-swift-nyc-2017-matt-gallagher-driving-view-state-through-data/</a></p><p><strong>Code:</strong> <a href="http://github.com/mattgallagher/Clocks">github.com/mattgallagher/Clocks</a></p><p>In this talk, Matt showcased an alternative implementation of the <a href="http://redux.js.org/">Redux</a>/<a href="https://github.com/ReSwift/ReSwift">ReSwift</a> Time Travel feature. What impressed me the most was the ability to drive the data/document state and presentation state separately. This could theoretically allow you to easily put the app into a state that’s otherwise very hard to enter.</p><p>Matt defined <em>view-state</em> as anything mutable in a view that isn’t written to the main “model.” For instance, each character of text typed into a search field is a piece of view-state, but doesn’t need to be saved to the main app-state each time the user enters a character.</p><p>While standard Cocoa apps treat view-state as a side-effect of presentation, Matt showed how inverting the paradigm to treat presentation as a <em>consequence</em> of view-state could allow these time travel features to be easily built.</p><p>The primary example Matt showed involves the common task of transitioning to a detail screen in an app. In the standard <em>presentation-driven</em> approach, a view controller would typically call performSegue(withIdentifier:) to initiate the transition and subclass prepare(for segue:sender:) to catch and set data on the view controller during the transition. In a <em>data-driven</em> approach, an update to the view-state is made and then the presentation is performed in response to the updated view-state.</p><p>Example code is shown below (sorry for the subpar photo quality):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*0lTmbYcMgpuvJGqNTYYjLw.png" /><figcaption>Inverted presentation logic — photo credit to <a href="http://twitter.com/cocoawithlove">Matt Gallagher</a></figcaption></figure><p>What impressed me the most was certainly the demo that Matt showed. I’ve created a quick video showcasing the standard time travel feature and then turning on the second slider to enable driving the main app-state and view-state independently of each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*XhMaGCnEgHB7aKpKLJQ8MQ.gif" /><figcaption>Demo of driving view-state independently from app-state in <a href="http://github.com/mattgallagher/Clocks">github.com/mattgallagher/Clocks</a></figcaption></figure><h4>Creating Rich Custom UI Notifications</h4><p><a href="https://twitter.com/thedevme"><strong>Craig Clayton</strong></a></p><p><strong>Video: </strong><a href="https://academy.realm.io/posts/try-swift-nyc-2017-craig-clayton-creating-rich-custom-ui-notifications/">https://academy.realm.io/posts/try-swift-nyc-2017-craig-clayton-creating-rich-custom-ui-notifications/</a></p><p><strong>Slides: </strong><a href="https://www.slideshare.net/thedevme/creating-rich-custom-ui-notifications">slideshare.net/thedevme/creating-rich-custom-ui-notifications</a></p><p><strong>Code:</strong> <a href="http://bit.ly/tryswiftcc">bit.ly/tryswiftcc</a></p><p>In Craig’s talk, he gave a great overview of what it takes to implement the custom notifications UI that was introduced in iOS 10. I’ve personally not implemented this feature yet, so it was awesome to get a “crash course” in their implementation.</p><p>Setup is as simple as implementing three methods:</p><ul><li>AppDelegate application(_:didRegisterForRemoteNotificationsWithDeviceToken:) — check if we’ve got permissions</li><li>UNUserNotificationCenterDelegate userNotificationCenter(_:willPresent:withCompletionHandler:) — called when the app receives a push while in the foreground</li><li>UNUserNotificationCenterDelegate userNotificationCenter(_:didReceive:withCompletionHandler:) — called when the app receives a push while in the background</li></ul><p>To enable your custom notifications to run, the value for themutable-content key on the aps push notification payload must be set to 1 (an Int).</p><pre>{<br> &quot;aps&quot;: {<br>  &quot;alert&quot;: &quot;New Message&quot;,<br>  &quot;mutable-content&quot;: 1<br> }<br>}</pre><p>New in iOS 11 is the ability to turn off the notification preview text, which means the user would see the text “Notification” instead of the alert message that you set on the push payload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*1qjC6e9oH2Tg2YnDDpWqBQ.jpeg" /><figcaption>You can turn off notification preview text in Settings -&gt; Notifications.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*QjBTlPhxJTtBeV7M67mc6w.png" /><figcaption>Turning off notification previews will cause push messages to display “Notification” by default.</figcaption></figure><p>In order to customize this text, your app can include a strings.dict plist that will pluralize the message. This would allow the message to read something like “3 new tweets” instead of just “Notification.” Check out Apple’s <a href="https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPInternational/LocalizingYourApp/LocalizingYourApp.html#//apple_ref/doc/uid/10000171i-CH5-SW10">Localizing Your App</a> documentation for more information.</p><p>Also new in iOS 11 is the thread-id key on the aps push notification payload. This allows iOS to automatically merge related messages. For example, subsequent game updates could be combined into one message that contained the latest score.</p><pre>{<br> &quot;aps&quot;: {<br>  &quot;alert&quot;: &quot;New Message&quot;,<br>  &quot;mutable-content&quot;: 1,<br>  &quot;thread-id&quot;: &quot;123&quot;<br>  }<br>}</pre><h4>Server-side Swift Using Vapor</h4><p><a href="https://twitter.com/tanner0101"><strong>Tanner Nelson</strong></a></p><p><strong>Video:</strong> <a href="https://academy.realm.io/posts/try-swift-nyc-tanner-nelson-server-side-swift-using-vapor/">https://academy.realm.io/posts/try-swift-nyc-tanner-nelson-server-side-swift-using-vapor/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*rxaGeLJxVI9Bt_-3WFgg_g.png" /></figure><p>Tanner started his talk with a general overview of the benefits to developing a server using server-side Swift technologies. He outlined the main downsides with the three most common solutions for backend development:</p><ul><li>CloudKit — built-in and easy to use, but not cross platform</li><li>MBaaS (Firebase, Realm, etc.) — hard to be <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a> across platforms since backend database update logic must be built-in to each client</li><li>Existing solutions (Express.js, Ruby on Rails, etc.) — are well established and supported, but will likely require you to learn a new language and tooling</li></ul><p>Compare this to server-side Swift, where you are working with a familiar language in your normal dev environment. Sharing models and business logic between the frontend and backend also helps you remain more DRY, and the compiler can help you type-check these interactions.</p><p>I toyed with Vapor about a year ago, but it was good to get a refresher on the main components of a Vapor server-side Swift application:</p><ul><li>Routing — sending HTTP request (and associated info) to your business logic handler</li><li>Object-relational mapping (ORM) — Fluent, the ORM in Vapor, allows you to easily fetch and persist data in a database as well as create and migrate schema</li><li>Leaf — templating language to render data to HTML (for creating web apps or sending emails)</li></ul><p>Another exciting aspect about Vapor’s evolution that Tanner mentioned was the improvements that Swift 4 brings with regard to reducing the amount of “stringly typed” code that you need to write and maintain.</p><h4>Modern RxSwift Architectures</h4><p><a href="https://twitter.com/krunoslavzaher"><strong>Krunoslav Zaher</strong></a></p><p><strong>Video:</strong> <a href="https://academy.realm.io/posts/try-swift-nyc-2017-krunoslav-zaher-modern-rxswift-architectures/">https://academy.realm.io/posts/try-swift-nyc-2017-krunoslav-zaher-modern-rxswift-architectures/</a></p><p><strong>Code:</strong> <a href="http://github.com/kzaher/RxFeedback">github.com/kzaher/RxFeedback</a></p><p>While I must admit that I have only surface knowledge of reactive frameworks like <a href="https://github.com/ReactiveX/RxSwift">RxSwift</a>, I did enjoy Krunoslav’s talk on <a href="https://github.com/kzaher/RxFeedback">RxFeedback</a>, even if I was a little lost at times. 😅</p><p>From what I understand, RxFeedback is a new architectural approach for reactive apps that use RxSwift. The main idea seems to be tying together an initial state, a reducer, and a “feedback loop” to help you build your app’s functionality in a standard, straightforward way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JNaoOxJXq4dWmqpgmDi9MA.png" /><figcaption>RxFeedback — photo credit to <a href="https://github.com/kzaher/RxFeedback">RxFeedback</a></figcaption></figure><p>One of the main benefits to using this architecture seems to be getting everyone on the same page and making it easy for developers to answer the question, “where do I need to put this code?”</p><ul><li>If it’s state/data → encode it into the main ‘state’ struct</li><li>If it’s a way to modify state → create an Event/Command</li><li>If it’s an effect → encode it into part of the state and then design a feedback loop</li></ul><p>As an example, consider the following simple counter component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*Mk6XqMNScFYorwUbdrHEuQ.gif" /><figcaption>A simple counter app — photo credit to <a href="https://github.com/kzaher/RxFeedback">RxFeedback</a></figcaption></figure><p>The state changes and UI binding can be succinctly described using RxFeedback:</p><pre>Observable.system(<br>    initialState: 0,<br>    reduce: { (state, event) -&gt; State in<br>            switch event {<br>            case .increment:<br>                return state + 1<br>            case .decrement:<br>                return state - 1<br>            }<br>        },<br>    scheduler: MainScheduler.instance,<br>    feedback:<br>        // UI is user feedback<br>        UI.bind { state in<br>            ([<br>                state.map(String.init).bind(to: label.rx.text)<br>            ], [<br>                plus.rx.tap.map { Event.increment },<br>                minus.rx.tap.map { Event.decrement }<br>            ])<br>        }<br>    )</pre><p>This looks promising if code like above can scale for a fully-fledged application. I’m definitely adding RxSwift/RxFeedback to my todo list to explore further in the coming months!</p><h4>Error handling made easy</h4><p><a href="https://twitter.com/elenipapanikolo"><strong>Helen Papanikolopoulou</strong></a><strong> &amp; </strong><a href="https://twitter.com/kostaskremizas"><strong>Kostas Kremizas</strong></a></p><p><strong>Video:</strong> <a href="https://academy.realm.io/posts/try-swift-nyc-2017-eleni-papanikolopoulou-kostas-kremizas-error-handling/">https://academy.realm.io/posts/try-swift-nyc-2017-eleni-papanikolopoulou-kostas-kremizas-error-handling/</a></p><p><strong>Code:</strong> <a href="https://github.com/workable/swift-error-handler">github.com/workable/swift-error-handler</a></p><p>Helen and Kostas showcased some great techniques to make error handling easier to manage with codebase growth. They first outlined the major problems with taking an adhoc, on-the-fly approach to error handling:</p><ul><li>Lots of boilerplate, repeated code (non-DRY)</li><li>No standardized way of handling errors across the codebase — different engineers will solve the problems in different ways</li><li>Complex code paths (e.g. multiple return statements) can lead to cognitive overload</li></ul><p>I also really loved the list of bad error handling practices that you should try to avoid:</p><ul><li>Skipping cases and/or using generic error messages — don’t be in a hurry/lazy (“I’ll fix it later”) or make the assumption that errors are edge cases.</li><li>Leaving duplicated/similar code everywhere</li><li>Handling errors directly in the networking layer</li></ul><p>On the contrary, some good practices for error handling include:</p><ul><li>Creating a set of default actions for common errors</li><li>Having an easy way to customize defaults</li></ul><p>Helen and Kostas introduced their <a href="https://github.com/workable/swift-error-handler">ErrorHandler</a> library and showcased how it can help bring sanity to your error handling. The general idea is to encapsulate all of your common error handling code into a default handler. Things like responding to no internet connection, 401 Unauthorized errors, and generic errors will typically be handled in the same way across your app. You can also specify actions that should always run any time an error is encountered, like sending the error to your logging mechanism.</p><pre>extension ErrorHandler {<br>    class var defaultHandler: ErrorHandler {<br><br>        return ErrorHandler()</pre><pre>            .on(NSErrorMatcher(domain: NSURLErrorDomain, code: NSURLErrorNotConnectedToInternet) { (_) in<br>                showErrorAlert(&quot;You are not connected to the Internet. Please check your connection and retry.&quot;)<br>                return .continueMatching<br>            }<br><br>            // You can use the Alamofire extensions to easily handle responses with invalid http status<br>            .onAFError(withStatus: 401, do: { (_) in<br>                showLoginScreen()<br>                return .continueMatching<br>            })<br><br>            // Handle unknown errors.<br>            .onNoMatch(do: { (_)  in<br>                showErrorAlert(&quot;An error occurred! Please try again. &quot;)<br>                return .continueMatching<br>            })<br><br>            // Add actions - like logging - that you want to perform each time - whether the error was matched or not<br>            .always(do: { (error) in<br>                Logger.log(error)<br>                return .continueMatching<br>            })<br>    }<br>}</pre><pre>}</pre><p>Then, in the caller (typically your view controller), you have much less boilerplate code to deal with. You can even override the error handling routines if you need custom behavior.</p><pre>sendMessage(message) { (response, error) in<br><br>            if let error = error {<br>                ErrorHandler.defaultHandler<br>                    .on(ValidationError.invalidEmail, do: { (_) in<br>                        updateEmailTextFieldForValidationError()<br>                        return .continueMatching<br>                    })<br>                    .onAFError(withStatus: 404, do: { (_) in<br>                        doSomethingSpecificFor404()<br>                        return .stopMatching<br>                    })<br>                    .onNoMatch(do: { (_) in<br>                        // In the context of the current screen we can provide a better message.<br>                        showErrorAlert(&quot;An error occurred! The message has not been sent.&quot;)<br>                        // We want to override the default onNoMatch handling so we stop searching for other matches.<br>                        return .stopMatching<br>                    })<br>                    .handle(error)<br>            }<br>        }</pre><h4>Everyone is Your User</h4><p><a href="https://twitter.com/dev_jac"><strong>Julio Carrettoni</strong></a></p><p><strong>Slides:</strong> <a href="http://speakerdeck.com/dev_jac/accessibility-everyone-is-your-user">speakerdeck.com/dev_jac/accessibility-everyone-is-your-user</a></p><p><strong>Code:</strong> <a href="http://github.com/Julioacarrettoni/tryswiftnycAccessibilityDemo">github.com/Julioacarrettoni/tryswiftnycAccessibilityDemo</a></p><p>In the final talk of the conference, Julio did an exceptional job showcasing a poor voice-over experience and the steps needed to make it better. Julio then kicked things up a notch by putting himself in the shoes of an accessibility user and performing his demo while blindfolded!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*eErYk9mLHZ7zU94o6G8ayw.png" /><figcaption>“The only thing worse than doing a live demo is doing a live demo while blind.”</figcaption></figure><p>There were some great accessibility tips given during this presentation:</p><ul><li>Use native elements when possible (don’t try to make a “look-alike” yourself).</li><li>Don’t rely on overlays to block interactivity. This doesn’t play well with the screen reader.</li><li>Don’t use “transparent” buttons on top of UI elements. This also doesn’t play well with the screen reader (although iOS 11 is a little more forgiving and will try to help).</li><li>Pay attention when using UIGestureRecognizers.</li><li>Watch out for the naming of image assets. If no accessibility description is given, the system will read the file name of the asset itself.</li><li>When in doubt, look to Apple’s apps for tips on how to adopt accessibility best-practices.</li></ul><h3>Other Cool Stuff at try! Swift</h3><h4>Machine Ethics and Emerging Technologies</h4><p><a href="https://twitter.com/pjf"><strong>Paul Fenwick</strong></a></p><p><strong>Video:</strong> <a href="https://academy.realm.io/posts/try-swift-nyc-2017-paul-fenwick-machine-ethics-emerging-technology/">https://academy.realm.io/posts/try-swift-nyc-2017-paul-fenwick-machine-ethics-emerging-technology/</a></p><p>While this talk wasn’t iOS or Swift related, it was one of my favorite talks of the conference! Paul provided great food for thought that we, as software engineers, need to keep in mind as the world continues to evolve with technological progress. Paul highlighted how ethics will become more important when designing autonomous systems like self-driving cars. At what point would it be okay for the self-driving car to sacrifice its occupant in order to save a pedestrian’s life? Would it ever be okay? Will we have two “types” of self-driving cars in the future — those that act with the “greater good” in mind and those that exclusively prioritize the safety of their occupants at all times?</p><h4>Buddybuild demo</h4><p><a href="https://twitter.com/dennispilarinos"><strong>Dennis Pilarinos</strong></a></p><p><strong>Video:</strong> <a href="https://academy.realm.io/posts/try-swift-nyc-2017-dennis-pilarinos-buddybuild/">https://academy.realm.io/posts/try-swift-nyc-2017-dennis-pilarinos-buddybuild/</a></p><p>While I’ve heard of <a href="https://www.buddybuild.com/">Buddybuild</a>, I’ve never used it before. I generally prefer to have complete control over my signing and build process, but Buddybuild is definitely on to something with how easy they’ve made it setup a new project, onboard testers, and allow them to provide feedback! It only took about 10 minutes to get an app onto the Buddybuild platform and deploy it to a random audience member.</p><h4>James Dempsey and the Breakpoints</h4><p><a href="https://twitter.com/jamesdempsey"><strong>James Dempsey</strong></a></p><p>James, who presented on the first day of the conference, helped to close out the show by performing some of his iOS development anthems. Armed with his ukulele and some clever lyrics, James’ tunes were a great way to end the conference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*5yiQNqpmZfIsQzOLTQ5tqQ.gif" /></figure><h3>Thanks, try! Swift!</h3><p>A quick thanks to <a href="http://twitter.com/NatashaTheRobot">NatashaTheRobot</a> for organizing the conference and all of the volunteers for making it happen! Also thanks to all of the <a href="https://www.tryswift.co/events/2017/nyc/#sponsors">try! Swift NYC 2017 sponsors</a>! I had a great time at the conference and was able to soak in a lot of great material. I hope to be able to attend next year and am excited to see this conference continue to grow over the coming years!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ad479179a1f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/atlas/try-swift-nyc-2017-recap-5ad479179a1f">try! Swift NYC 2017 Recap</a> was originally published in <a href="https://medium.com/atlas">Atlas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Multiple Firebase Environments in iOS]]></title>
            <link>https://medium.com/atlas/using-multiple-firebase-environments-in-ios-12b204cfa6c0?source=rss-6a77f6e4f041------2</link>
            <guid isPermaLink="false">https://medium.com/p/12b204cfa6c0</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[environment]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Tyler Milner]]></dc:creator>
            <pubDate>Mon, 07 Aug 2017 22:32:13 GMT</pubDate>
            <atom:updated>2019-07-06T02:04:22.274Z</atom:updated>
            <content:encoded><![CDATA[<p>The Firebase suite of products is great for getting basic mobile backend services up and running quickly. One of the most common Firebase services is Google Analytics for Firebase, which allows you to setup and track actions that users are performing in your app. The deeper you invest in setup of analytics events, the more accurately you can start to understand user behavior and react appropriately. Sometimes, this might mean making business-critical decisions based on this information, which makes the accuracy of said information of the utmost importance. In this post, I’ll outline the problem of analytics “data pollution” and then walk you through the process of setting up your Xcode project to enable separate Firebase development and production environments.</p><h3><strong>Data Pollution</strong></h3><p>One potential source of pollution to your analytics data could be from your own QA process when developing and testing your app. If analytics data capture is not suppressed during the testing process, then your testers could be over-exaggerating certain user flows, giving you a false image of how your actual users are actually using the app. Sure, you could probably work around this by setting up some clever rules to try and filter out the invalid data before analysis, but wouldn’t it be better if the data never made it into your production environment in the first place?</p><p>Another source of pollution could live in the Firebase Analytics console itself. During the development process, you may want to experiment with setting up new funnels, audiences, or filters in response to the creation of new analytics events or application features. In this case, suppressing the analytics events would prevent you from being able to do proper prep-work inside the console. You also don’t want to pollute your production Firebase Analytics console with fragments and configurations leftover from your development and testing process.</p><h3><strong>Separate Firebase Environments — Existing Solutions</strong></h3><p>Surprisingly, setting up separate Firebase development and production environments isn’t very well documented, and some popular techniques could have unintended consequences.</p><p>One of the <a href="https://gist.github.com/cohenadair/3a2aff5084603bfa65824f09cf74206e">first results</a> when you may come across when researching a solution involves creating two separate Firebase <em>projects</em>, which ultimately yields two separate GoogleService-Info.plist files. It’s then recommended to bring these both into your Xcode project, renaming the file that corresponds to your development Firebase environment with a “-Dev” suffix. A compilation condition check is then implemented in the code to manually start up the Firebase SDK with the contents of the appropriate GoogleService-Info.plist file.</p><p>It’s important to note that this approach <em>will</em> work. The Firebase iOS documentation even recommends it when setting up a single app target to work with multiple Firebase environments. However, the <a href="https://firebase.google.com/docs/configure/#support_multiple_environments_in_your_ios_application">Firebase documentation</a> also warns developers that utilizing this approach can impact analytics collection in some circumstances. This is due to the fact that the Firebase SDK collects events very early in the application launch flow, in some cases before the primary Firebase app instance has been configured. In this scenario, the SDK uses the default name of the configuration file — GoogleService-Info.plist — to log these events. This means that the SDK could potentially be using the wrong configuration file briefly before your code is given a chance to configure the Firebase instance properly.</p><p>In most cases, this drawback probably will not pose any issues to your app. Firebase has explained the caveats to this approach in their <a href="https://firebase.google.com/docs/configure/#reliable-analytics">documentation</a>. However, even if your app won’t be affected by the potential drawbacks, you may want to go ahead and setup your project so that it removes the risk of them ever becoming an issue.</p><h3><strong>Separate Firebase Environments — An Alternate Approach</strong></h3><p>The first few steps of the current approach to setting up separate development and production Firebase environments are correct. To start off, you’ll still want to:</p><p>1. Create two separate <em>Projects</em> (not <em>Apps</em>), configuring each one to use the Bundle ID for your app target in Xcode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*q1f9D_PERel8rZUWQqBQvQ.png" /><figcaption>Create two new <strong>projects</strong> in Firebase — one for dev and one for prod.</figcaption></figure><p>2. In the Firebase console, create an <em>iOS App</em> for each Firebase project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*PlTfIXJ7Fzc_2zEsjbGeAw.png" /><figcaption>Create an <strong>iOS</strong> app for each project in Firebase.</figcaption></figure><p>3. In the Firebase console, download the GoogleService-Info.plist for each app, saving them to separate directories on your hard drive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJwhx0_tonPTcOzArz0JHA.png" /><figcaption>Download the <strong><em>GoogleService-Info.plist</em></strong> for each project.</figcaption></figure><p>For this setup process, instead of renaming one of the files to GoogleService-Info-Dev.plist, we’ll keep the name of the configuration files to their default value of GoogleService-Info.plist. This is to prevent us from having to manually configure the Firebase SDK instance during the app launch process, which will prevent the potential caveats with this approach from ever coming into the picture. To keep the default names for the plist configuration files, we’ll need to keep them in separate directories on the file system:</p><p>4. Inside of the directory corresponding to your app target’s code (usually the same directory that contains your AppDelegate.swift, Assets.xcassets, and Info.plist files), create a Firebase directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*kIHj6cyO7DNqMVRJEQ3rSw.png" /><figcaption><strong>Firebase</strong> directory created in main target directory.</figcaption></figure><p>5. Inside of the Firebase directory, create Dev and Prod child directories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*dpvN6paN9ixg-l58dwyF_w.png" /><figcaption><strong>Dev</strong> and <strong>Prod</strong> subfolders created.</figcaption></figure><p>6. Copy the GoogleService-Info.plist corresponding to your Firebase <strong>development</strong> environment into the Dev directory. Similarly, copy the GoogleService-Info.plist corresponding to your Firebase <strong>production</strong> environment in the Prod directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*JB8bZe9wjhGJSMdSuJidrw.png" /><figcaption>Copy the development plist into <strong>Firebase/Dev</strong> and the production plist into <strong>Firebase/Prod</strong>.</figcaption></figure><p>This next step is optional. If you’re like me, you appreciate it when an Xcode project’s “Group” structure matches the folder structure on the file system:</p><p>7. Add the Firebase folder to your Xcode project. Since this is the parent directory, it should automatically bring in the Dev and Prod child directories and their corresponding GoogleService-Info.plist files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PkJAM4VopaF-7FzQNSBdtg.gif" /><figcaption>Drag the <strong>Firebase</strong> folder into Xcode to add it to the project.</figcaption></figure><p>8. Make sure to <strong>uncheck</strong> “Copy items if needed” and all targets under “Add to targets”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*p0CeIBAyE7E01w7Pb1A58Q.png" /><figcaption>Add the <strong>Firebase</strong> folder to your Xcode project, unchecking “Copy items if needed” and “Add to targets”.</figcaption></figure><p>If you accidentally add either of the GoogleService-Info.plist files to your target, you can open up the <em>Utilities Panel</em> (right side) and uncheck the files from any targets that may be in there:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*h7eDd_ChH2Mi522jgVnKJg.png" /><figcaption>Each GoogleService-Info.plist should <strong>not</strong> belong to any targets.</figcaption></figure><p>When all is said and done, your Xcode project structure should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*p3qjB4PY721qP9CIBI3TSA.png" /><figcaption>Xcode project structure showing plist files inside of Firebase/Dev and Firebase/Prod directories.</figcaption></figure><p>You may be wondering why the GoogleService-Info.plist files aren’t being added to the app target. Indeed, they <em>do</em> need to be present in the final app bundle so that the Firebase SDK instance can be configured correctly. When the files are part of the app target, this happens automatically. However, because both files are named the same, we wouldn’t want both of them to automatically be copied into the app bundle. Instead, we’ll copy the files manually using an Xcode Run Script Build Phase:</p><p>9. In the Xcode project navigator, select the app target. Switch to the Build Phases tab at the top, then add a <strong>New Run Script Phase</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*YVsIb3As061yIAv6oG8Qbg.png" /><figcaption>Create a new “Run Script Phase” for your target.</figcaption></figure><p>10. Name the phase “Setup Firebase Environment GoogleService-Info.plist”, or something to that effect, and place it <em>before</em> the “Copy Bundle Resources” step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*e3wrUk5juhXiTH0DMpRuNw.png" /><figcaption>Rename the run script phase and place it before “Copy Bundle Resources”.</figcaption></figure><p>11. Implement a shell script that will copy the appropriate GoogleService-Info.plist into the app bundle based on the build configuration. Copy and paste the following shell script into the run script phase you just created:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28c9072a7b64944b1756f8b76fd5e717/href">https://medium.com/media/28c9072a7b64944b1756f8b76fd5e717/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*zJBnEUz1k3FZAdsDCtwJvg.png" /><figcaption>Paste the above script into the run script phase.</figcaption></figure><p>You may need to tweak the script for your own project. The script assumes that you have the default “Debug” and “Release” configurations in your project. The production GoogleService-Info.plist will be used for “Release” builds and the development GoogleService-Info.plist will be used for all other build configurations.</p><p>12. Follow the <a href="https://firebase.google.com/docs/ios/setup#add_the_sdk">Firebase SDK setup instructions</a> to add the Firebase SDK to your project if it’s not already been added. Skip the step to add the GoogleService-Info.plist to your project since you’ve already done that. Also, don’t forget to initialize the SDK in your AppDelegate’s application:didFinishLaunchingWithOptions: method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*7k50XsU37zthFYOdC8TBLw.png" /><figcaption>Initialize the Firebase SDK inside the AppDelegate.</figcaption></figure><p>13. Check to make sure everything works properly:</p><p>Build your app and ensure the build process finishes without any errors. Then, right-click on the .app file in the <em>Products</em> group in Xcode and select <strong>Show in Finder</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*OEmSgojxapvi3Sp8FOZFtA.png" /><figcaption>Build the project, right-click on the generated .app, and select “Show in Finder”.</figcaption></figure><p>Then, in Finder, right-click the <em>.app</em> file and select <strong>Show Package Contents</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*RUyFPWf_J-SWLHcjTWYnuw.png" /><figcaption>Right-click the .app and select “Show Package Contents”.</figcaption></figure><p>If all went well, you should see a GoogleService-Info.plist. Open it up and verify that the values match that of your development GoogleService-Info.plist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*yINnGQFCGW9RJZCrT724ow.png" /><figcaption>Verify the contents of the GoogleService-Info.plist inside of the app bundle are what you expect.</figcaption></figure><p>Next, perform some final validation to make sure your production GoogleService-Info.plist will be used for “Release” build configurations. Change your <em>Run</em> scheme to “Release” and build your app again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*igNq8VU1V4qG1m8nhoF5Xg.png" /><figcaption>Temporarily edit your scheme to use the “Release” build configuration.</figcaption></figure><p>Crack open the .app again and verify that the GoogleService-Info.plist matches your production version. At this point, you should be good to go. Don’t forget to change your <em>Run</em> scheme back to “Debug” before you actually run your app and continue development.</p><h3><strong>Conclusion</strong></h3><p>That’s it! Your Xcode project is now configured to swap out your GoogleService-Info.plist based on build configuration. This will keep all of your development and production Firebase Analytics data separate so that you won’t have to worry about polluting your production analytics data when developing or testing debug versions of your app.</p><p>If you’d like to see all of the pieces in action, a fully configured <a href="https://github.com/tylermilner/FirebaseEnvironmentsDemo">sample project is available on GitHub</a>. The latest version of the shell script used to selectively copy the GoogleService-Info.plist is also available as a <a href="https://gist.github.com/tylermilner/f8e9121d62c890cb707bc1810a7d57d9">GitHub Gist</a>. At the time of writing, the following tools were used to generate this guide:</p><ul><li>Xcode 8.3.3</li><li>Cocoapods 1.3.0.beta.2</li><li>Firebase iOS SDK 4.0.3</li></ul><h4><em>Updated July 2019</em></h4><p>The sample project has been updated for Xcode 10 and Firebase 6.x. Improvements to the README and sample app have also been made.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12b204cfa6c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/atlas/using-multiple-firebase-environments-in-ios-12b204cfa6c0">Using Multiple Firebase Environments in iOS</a> was originally published in <a href="https://medium.com/atlas">Atlas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>