<?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 Josh Marasigan on Medium]]></title>
        <description><![CDATA[Stories by Josh Marasigan on Medium]]></description>
        <link>https://medium.com/@joshmarasigan?source=rss-57c4402ff511------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*b6QqsbEsBFusqXNcF8--KA@2x.jpeg</url>
            <title>Stories by Josh Marasigan on Medium</title>
            <link>https://medium.com/@joshmarasigan?source=rss-57c4402ff511------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 21:55:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joshmarasigan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The why, what, and how of Swift Auto-Layout]]></title>
            <link>https://uxdesign.cc/the-why-what-and-how-of-swift-auto-layout-9530a60eedf4?source=rss-57c4402ff511------2</link>
            <guid isPermaLink="false">https://medium.com/p/9530a60eedf4</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[autolayout]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Josh Marasigan]]></dc:creator>
            <pubDate>Sat, 20 Jun 2020 23:16:38 GMT</pubDate>
            <atom:updated>2020-06-22T01:38:58.214Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u-t0Vy02p9-KPFNckKUCTA.png" /></figure><p><em>I think people are a lot like UI components on a phone. In a way, we’re all trying to find our place in this bezel-less screen we call life.</em></p><p><em>We want to find where we’re meant to be in this world, where we can grow and fill the space around us with our potential, or where we can settle to make room for others.</em></p><p><em>We might not ever fill these longings in life, but at the very least, we can find solace in knowing that iOS components using Auto-Layout have found their place in theirs.</em></p><p>We’re going to take a look at why Auto-Layout exists, how it works, and some ways we can use it to configure dynamic UI (before things like VStacks, Spacers, and TikTok existed).</p><p>You’ll see that working with Auto-Layout not only teaches us how to make rectangles show up on a screen, but also leaves us a few life lessons along the way. Get comfortable, play some lo-fi, and let’s embark on this introspective journey together 🧘🏽‍♂️ —</p><h3>Why Auto-Layout? 😶</h3><p><em>To fully understand what Auto-Layout is, we first have to look at the problem it’s trying to solve.</em></p><p><strong>Frames 🖼</strong></p><p>Originally, views give superviews context by setting an explicit <strong>position and size</strong> (a <a href="https://developer.apple.com/documentation/uikit/uiview/1622621-frame">frame</a>) in order to place themselves on-screen.</p><p>The superview takes this context and tells its coordinate system exactly where and how large it should display.</p><p><strong>What we’re going to do — </strong>Using an iPhone 8, we want to display two <em>identically</em> sized squares next to each other and fill to screen width. We’re going to apply 20<strong> </strong>points of padding to the left and right side of the squares, as well as 20 points in between:</p><pre><strong><em>Justifications:<br></em></strong><em>An iPhone 8’s point dimensions are 375 x 667</em></pre><pre><strong><em>view1</em></strong><em> </em><strong><em>x-origin = 20 </em></strong><em>(Full left padding)</em></pre><pre><strong><em>view2 x-origin = 375/2 + 10 = 197.5</em></strong><em> (Centered with half-padding)</em></pre><pre><strong><em>Both</em></strong><em> </em><strong><em>width/height = 375/2 - 20 - 10 = 157 </em></strong><em><br>(Half the screen width without left and right side paddings)</em></pre><pre><strong><em>Both y-origins = 250</em></strong><em> (Arbitrary for our requirements)</em></pre><p>After applying the most math I’ve done since refinancing my student loans, we find exactly what origin and dimension values we need in order to make the context for our superview.</p><p>We’ll then create a CGRect frame with these values to instantiate our UIViews with. Now when we add these views to any arbitrary superview, that superview will use this frame to lay it out <em>in its own coordinate system</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7484dd120e232f48c70cc57043635285/href">https://medium.com/media/7484dd120e232f48c70cc57043635285/href</a></iframe><p>It doesn’t matter at which point in the code we add these views as subviews, since it’s the views themselves that holds the information of their frames.</p><p>We can technically add these subviews until the last configuration lines and it’ll still display correctly!</p><p>Now that we have our views, let’s run the app and see how it goes —</p><figure><img alt="Figure 1.A" src="https://cdn-images-1.medium.com/max/375/1*AySAXOrKDUowS5gng2dZTQ.png" /><figcaption>iPhone 8 (375 x 667)</figcaption></figure><p>Looks good <strong>👍🏽</strong></p><p>Since we were specific in where and how large to place <strong>view1</strong> and <strong>view2</strong>, we see that the superview sets them as expected.</p><p>If there’s no anticipated changes in the UI, then each subview’s frame will always be relevant to the context of its superview’s coordinate system.</p><p>But what happens when the superview’s frame changes, or even of one of its subviews? Let’s run the app again with the same values, but this time with an iPhone 11 Max <em>—</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*KjYxVkCWljWbDRie9haHDA.png" /><figcaption>iPhone 11 Pro Max (414 x 896)</figcaption></figure><p>Oh no 🤭</p><p>Since the superview’s frame changed from <em>375x667</em> to <em>414x896</em>, our original calculations based on the iPhone 8 dimensions failed to scale.</p><p>Sure we can make a constant for the width value to something like the UIScreen’s width, but what if the culprit of the change is the subview’s content? 🙊</p><p>We won’t know how to accommodate the subview’s frame from the super’s perspective without some serious effort.</p><p>And as self-proclaimed “good programmers”, we hate effort. Specially the serious kind.</p><p>Accommodating phone sizes, anticipating dynamic view content, or even adjusting for landscape mode can be very annoying when recursively calculating the frames in your view hierarchy.</p><h3>—</h3><h3>What is Auto-Layout exactly? 💀</h3><p><em>That’s why Auto-Layout exists. By using constraints to represent the relationship between views, Auto-Layout generates these frames for you. It calculates the size and position on your behalf as long as the rules you set (the constraints) result in one sound outcome.</em></p><p><strong>Constraints and Attributes ⛓</strong></p><p>In short, <a href="https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/AutolayoutPG/AnatomyofaConstraint.html#//apple_ref/doc/uid/TP40010853-CH9-SW1">constraints</a> are the relationship between one or two participating view’s edges, sizes, or centers, usually with some sort of modification like an offset or multiple. They’re the building blocks of Auto-Layout.</p><p><em>To represent the ‘something’ that pins views together, we sort them into distinct categories. We can just call the ‘somethings’ attributes.</em></p><pre><strong>Attribute Categories —</strong></pre><pre><strong><em>Horizontal: </em></strong><em>Left, Right, Leading, Trailing, and Center-X</em></pre><pre><strong><em>Vertical: </em></strong><em>Top, Bottom, and Center-Y</em></pre><pre><strong><em>Size: </em></strong><em>Height and Width</em></pre><p><em>Note: </em><strong><em>Leading and Trailing</em></strong><em> are functionally similar to </em><strong><em>Left and Right</em></strong><em>, but can change depending on device locale. A leading anchor is left to the view in USA locales, but right in Japanese locales. Vice-versa for trailing. Use them instead of left and right constraints if you need to localize your app for these locales. </em>🔀</p><p>Now that we have our attributes, let’s take a look at applying them! I like to think of the anatomy of a constraint in roughly <strong><em>three parts</em></strong> 🍡 —</p><pre><strong><em>Participants: </em></strong><em>The one or two participating attribute(s)</em></pre><pre><strong><em>Inequalities: </em></strong><em>The type of relationship between participant(s)</em></pre><pre><strong><em>Modification: </em></strong><em>Some sort of optionally applied defined change</em></pre><p>You can also only set constraints between ones in each category, meaning you can’t pin a view’s top constraint to another view’s left and so on.</p><p>Let’s take a look at how a constraint is made with a basic NSLayoutConstraint. Referencing our squares example, we’re going to pin the left side of the first square to the left side of the superview:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/717949280bbd54c8e93a72e92be0a275/href">https://medium.com/media/717949280bbd54c8e93a72e92be0a275/href</a></iframe><p><em>Note: In order to let Auto-Layout know you wish to use this constraint, you need to set the constraint’s </em>isActive<em> property to </em><strong><em>true</em></strong><em>.</em></p><ul><li><em>The </em><strong><em>participants</em> 👬 </strong><em>in this constraint are </em><em>view1 and its superview (the view controller’s view).</em></li><li><em>The </em><strong><em>inequality </em>⚖️ </strong><em>is indicated by the relatedBy parameter, and in this case set to </em><em>equal, but can also be set to </em><em>lessThanOrEqual or </em><em>greaterThanOrEqual. This means that if a constraint needs to grow or shrink due to some frame change, you’re giving it permission to do so.</em></li><li><em>The </em><strong><em>modifications </em>🏎 </strong><em>in this constraint is an offset of 20, meaning </em><em>view1’s left is going to be equal to view’s left, but shifted to the right by 20 points. The multiplier is also a modification, but since we’re not dealing with sizes, it doesn’t make sense to change it.</em></li></ul><p>There’s one cardinal rule when it comes to working with constraints. They all have to play nice with each other, meaning constraints generally need to <em>implicitly</em> convey the position and size of your view, instead of <em>explicitly</em> like our frames did.</p><p>The superview still needs a size and position for their subviews, so constraints need to provide that information. The only difference is that information is given through relationships, not through hard numbers. Because why do math when you can do not-math? 💩</p><p><strong>The game plan — </strong>Our constraints for our original example will look like this:</p><pre><strong><em>Left square:</em></strong></pre><pre><em>The left attribute must equal the superview’s left + 20 points</em></pre><pre><em>The top attribute must equal the superview’s top + 250 points</em></pre><pre><em>The width must equal the super&#39;s width divided by 2 - 30 points</em></pre><pre><em>The height attribute must equal its own width attribute</em></pre><pre><strong><em>Right square:</em></strong></pre><pre><em>The left attribute must equal the left square’s right + 20 points</em></pre><pre><em>The height and width attribute must equal the left’s</em></pre><pre><em>The centerY attribute must equal the left square’s centerY attribute</em></pre><p><em>Note: Since the coordinate system for any view originates from the top-left corner (where origin = CGPoint(x: 0, y: 0)), all positive offsets will shift a constraint in the down/right direction, while negative offsets shift in the up/left direction.</em></p><p>Let’s break this down per object —</p><p><strong>Left Square:</strong></p><ul><li><em>We define the </em><strong><em>size</em></strong><em> by indicating the </em><strong><em>width</em></strong><em> as equal to the super’s width along with an offset of -20 points applied, and the </em><strong><em>height</em></strong><em> equal to its own width (or equal to the same constraint our width depends on).</em></li><li><em>We define the </em><strong><em>position</em></strong><em> by indicating it must equal to the super’s left attribute </em><strong><em>(x-axis)</em></strong><em> with a 20 point positive offset to shift it to the right, and equal to the super’s top attribute </em><strong><em>(y-axis)</em></strong><em> with a 250 point positive offset to shift it down the screen.</em></li></ul><p><strong>Right Square:</strong></p><ul><li><em>We can imply where the </em><strong><em>position</em></strong><em> is because we know how far left </em><strong><em>(y-axis)</em></strong><em> it needs to be by making its left attribute equal to the other square’s right attribute (with padding), as well as how for down </em><strong><em>(x-axis)</em></strong><em> by making its y-center attribute equal to the left square’s y-center.</em></li><li><em>We know the </em><strong><em>size</em></strong><em> of it by setting its </em><strong><em>width</em></strong><em> and </em><strong><em>height</em></strong><em> constraint equal to the left’s size.</em></li></ul><p>No rules are being broken by these relationships, but let’s say we leave out the second requirement for the right square. Now Auto-Layout doesn’t know how large the right square needs to be anymore.</p><p><strong>It doesn’t play nice.</strong> This is going to cause some issues during <em>run-time</em>, since in most cases the compiler won’t throw a fit over some missing constraints. We give the <strong>position</strong> of the right square, but not the <strong>size</strong>. Constraints need to fulfill both, since it’s going to be rendered down to frames later on! 😮</p><h3>—</h3><h3>How do we implement Auto-Layout? 🤭</h3><p>There’s plenty of tools when it comes to Auto-Layout. Through trial, error, and deprecation, we find a set of practical approaches for modern day layout development —</p><ul><li><em>We can do it programmatically, with </em><strong><em>NSLayoutAnchor </em></strong><em>(the successor of NSLayoutConstraint after iOS 8</em><strong>*</strong><em>)</em></li><li><em>We can do it visually, with </em><strong><em>Interface Builder</em></strong><em> </em><strong><em>(IB) </em></strong><em>and Storyboards</em></li><li><em>Or we can even take a non-native approach with </em><strong><em>third-party kits and DSLs</em></strong><em> like SnapKit, which is built on top of native constraints</em></li></ul><p><strong>*</strong><em>Since we’re currently at iOS 13, let’s assume we’ll just need to run iOS 10+</em></p><p>Picking the right Auto-Layout tool can be tricky. We need to really reflect on why Apple and friends felt the need to give us so many (it could be for no reason honestly). But there probably is a reason! So which ones do we choose? <em>Which ones Josh??</em> <strong><em>What was the reason?? WHAT WAS THE REASON??</em></strong></p><h4>NSLayoutAnchors 🧘🏽‍♂️</h4><blockquote>You’ve got to find yourself first. Everything else’ll follow — Charles De Lint</blockquote><p>You know how I mentioned that constraints need to have participants in the same attribute category? Before NSLayoutAnchors, its predecessor NSLayoutConstraint didn’t have any checks on the constraint category of its attribute parameters.</p><p>This means that you can compile <strong>and</strong> run a constraint that pins a view’s right to another view’s top (which crashes your app)! 😬</p><p>To fix this, and to provide a more concise syntax, NSLayoutAnchors were given the power of <em>self actualization</em>. They were built with type-safety in mind and only sets constraints between attributes <em>of the same category</em>. 🤝</p><p>The anatomy of an NSLayoutAnchor can be skimmed down to —</p><pre>&lt;<strong>someView</strong>&gt;.&lt;<strong>someAnchor</strong>&gt;.constraint(&lt;<strong>someInequality</strong>&gt;: &lt;<strong>nextAnchor</strong>&gt;)</pre><p><em>Note: The </em>someAnchor<em> param and </em>nextAnchor<em> must be of the same category, or the compiler will throw up before you get the chance to run and crash —</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kraIktwfuo3mHRqgZM6v8Q.png" /></figure><p>The parameters are also a <em>subset</em> of the full parameter list in NSLayoutConstraint, which means less code and less ambiguity.</p><p>You ask for what you just need, and if you need something extra, they have a full list of convenience inits to compensate for fewer parameters.</p><p>So back to the squares, but this time with our new friend<em> </em>NSLayoutAnchor ⚓️</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f44edbc8fc3979fac25e3aa8c302813/href">https://medium.com/media/8f44edbc8fc3979fac25e3aa8c302813/href</a></iframe><p>There’s one thing we need to do before setting up our constraints. Since we don’t want <a href="https://developer.apple.com/documentation/uikit/uiview/1622559-autoresizingmask">autoresizing masks</a> to interference with Auto-Layout in creating constraints, we want to set the participating views’ translatesAutoresizingMaskIntoConstraints values to false.</p><pre><em>view1.</em><strong><em>translatesAutoresizingMaskIntoConstraints</em></strong><em> = false</em></pre><p>Let’s highlight some of the NSLayoutAnchor functionality above —</p><p>Earlier we mentioned how parameters are in a need to know basis, so we see below that a constant parameter can be appended to the list if you need to add optional padding (which also compiles and runs without it)!</p><pre><em>view1.topAnchor.constraint(</em><strong><em>equalTo</em></strong><em>: view.topAnchor, <br>                           </em><strong><em>constant</em></strong><em>: 250).</em><strong><em>isActive = true</em></strong></pre><p>Below, leadingAnchor and trailingAnchor are of the same category (horizontal), so the compiler accepts this as a valid constraint —</p><pre><em>view2.</em><strong><em>leadingAnchor</em></strong><em>.constraint(equalTo: view1.</em><strong><em>trailingAnchor</em></strong><em>, <br>                               constant: 20).isActive = true</em></pre><p>Also along with constants, multipliers can be inserted in the parameter list in situations where you need a scaled relationship between two <strong>size</strong> attributes.</p><pre><em>view1.widthAnchor.constraint(equalTo: view.widthAnchor, <br>                             </em><strong><em>multiplier</em></strong><em>: 0.5, <br>                             constant: -30).isActive = true</em></pre><p>We run the app and see that it displays perfectly on an iPhone 11 Pro Max! 🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*GsbhW5Bmf0lTVCVicfaK6g.png" /></figure><h4>Storyboards &amp; IB 🗺</h4><blockquote>“If you can dream it, you can do it.” — Walt Disney</blockquote><p>There’s a certain sense of gratification when you see your final product after spending so much time fine-tuning it. As someone whose attention span has been permanently ruined by modern media, I could care less.</p><p>I want that sweet-sweet instant gratification for what I’m doing right here, right now, yesterday, the day before, last year, before I was born —</p><p>That’s the cool thing about Storyboards: You see what you get. There’s no frills, you click and drag constraints, and Interface Builder (the editor that Storyboard runs on) updates the UI in real time!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*XKvXTZ9F32X1ADpYYJXNWg.gif" /><figcaption>Figure 1.A</figcaption></figure><p>The view controller for this example has our two squares as subviews to its content view via IB.</p><p>Constraints between views can be created by hovering over one view and clicking control and dragging to a second view (or itself).</p><p>Release it and a tooltip appears where you can select the attribute(s) for the constraint created between these views, setting our <strong>participants.</strong></p><p>Once you create your constraint, you can also edit them in the interface on the right hand side in order to fine tune it. You’re given the option of changing your items (<strong>participants</strong>), changing your relation (<strong>inequalities)</strong>, or changing your constants/multipliers (<strong>modifications</strong>), all within one convenient toolbox!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*5jzwZ17N_rlSGuAqy7griw.gif" /><figcaption>Figure 1.B</figcaption></figure><p>Below is the same line of code in <em>Figure 1.A</em> that we implemented in IB with just one click and drag:</p><pre><em>view1.</em><strong><em>leadingAnchor</em></strong><em>.constraint(equalTo: view.</em><strong><em>leadingAnchor</em></strong><em>,<br>                               constant: </em><strong><em>20</em></strong><em>).isActive = true</em></pre><p>If you need more control of the constraint outside of IB, we can even create an IBoutlet if we need to update any properties (ie. isActive) during runtime in code —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*OVzHC9GB1RoObMW66rLTGw.gif" /></figure><p>We don’t even need to set the participating views’ translatesAutoresizingMaskIntoConstraints property since IB takes care of that for us.</p><p>Let’s recreate all the constraints we have for our NSLayoutAnchor example in Storyboard. We see that the constraints we created via drag and drop appear on the right hand side of the editor under the constraints tab for that view—</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bc2IVz_RntzW5ZU62q1QkA.png" /></figure><p>The interface here is super helpful with its line guides. We see how each constraint is applied to the view, even with the padding indicated. ✨</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HDcPdyQcQEBju3W-jg3JOw.png" /></figure><p>This is a very powerful visual tool that we don’t get through programmatic approaches. If we have any conflicting constraints, IB lets us know right away by highlighting in red any breaking constraints.</p><p>Storyboards have their own set of benefits over a programmatic approach.</p><ul><li><em>Navigation is explicitly indicated, making your view controller flows have visual representations.</em></li><li><em>You will write </em><strong><em>significantly less code</em></strong><em>, making this method super appealing for codebases that suffer from view layers that require more UI logic.</em></li><li><em>Because of that, it’s a great fit for design patterns that preach about single responsibility. (MVVM, VIPER, MVLMNOP, QRS, TUV)</em></li></ul><p><em>Note: Storyboards get transcribed to XML, and in some instances this might not play well with version control. This can definitely be mitigated by practices like using multiple storyboards, or not committing the automatic updates IB applies when you open it.</em></p><p>We run the app and see (<em>to no surprise</em>) that the UI has rendered exactly how IB displayed —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*XsdThRIjDGPEncztbUGxhA.png" /></figure><h4>SnapKit &amp; Third-Parties 👉🏽👈🏽</h4><blockquote>There is no need to suffer silently and there is no shame in seeking help. — Catherine Zeta-Jones</blockquote><p>I love SnapKit so much. If there weren’t any significant pros and cons between choosing a UI tool for a project, I’d go with SnapKit more times than I’d like to admit. 💩</p><p>Seems a bit excessive (and irresponsible), but the syntax is just <em>so nice</em>. Although I know.. No matter how nice a toolkit is, or how convenient it is to write layout code in fewer lines, SnapKit (and friends) are still third party.</p><p>Bringing in a dependency to your app can be a big decision. If you choose one that ends up being unsupported in newer versions of iOS, it can tie down your app to the previously supported version until you find a solution. This forces you to either remove that dependency and implement a native fix, or fork the dependency and fix it yourself. 🤡</p><p>With first party solutions like NSLayoutAnchor readily available for recent iOS versions, it’s getting hard to justify going third party. Sure you get more out of the box with something like SnapKit, but I found that most of what you need is already within UIKit. <em>(Nick if you’re reading this, I regret nothing)</em></p><p>And if there’s anything extra that’s missing in your app level toolkit, you can always write an extension or app level util to accommodate.</p><p>So with that disclaimer out of the way, we can get into why SnapKit is the best solution for any product, any use case, any iOS version in the past, present, and all future timelines that involves an iPhone.</p><p>The syntax for creating a constraint can be divided into the following —</p><pre>&lt;<strong>someView</strong>&gt;.snp.makeConstraints &lt;<strong>Make Closure</strong>&gt;</pre><p>Each UIView will have a property called snp which is provided by SnapKit. You can either call makeConstraints, updateConstraints, or remakeConstraints.</p><p>As the name suggests, SnapKit not only lets you create constraints initially, but also lets you update all/remake a subset of the constraints indicated inside your <strong>Make Closure</strong>:</p><pre><strong>Make Closure</strong> = ((<strong>MakeObject</strong>) -&gt; Void)</pre><p>After calling your intended constraint method, you’ll have to create your constraints inside the trailing closure provided.</p><p><em>Note: All constraints inside of it will activate </em><strong><em>automatically</em></strong><em>, meaning you’ll have to create some sort of reference to your SnapKit constraint (the </em>Constraint<em> object) in order to call </em>deactivate()<em> (which is their way of setting the </em>isActive<em> property to </em>false<em>).</em></p><p>Constraints in SnapKit follow a minimalist syntax —</p><pre>$0.&lt;<strong>Attribute</strong>&gt;.&lt;<strong>Inequality</strong>&gt;(&lt;<strong>Attribute</strong>&gt;).&lt;<strong>Optional Modification</strong>&gt;</pre><p>You can set the <strong>participants</strong>, <strong>inequality</strong>, and optional <strong>modifications</strong> all in one short line. 😮</p><p>Below, we recreate our squares example one last time —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8583d367bec1fc19942d20bbc264f99/href">https://medium.com/media/b8583d367bec1fc19942d20bbc264f99/href</a></iframe><p>There’s a lot of ~🆒~ things going on here.</p><p>First, you can <em>chain</em> constraints together so you won’t have to write multiple lines. This is super useful if you have a certain view’s attributes that have some sort of even relationship to another view’s single attribute —</p><pre><em>make.</em><strong><em>width</em></strong><em>.</em><strong><em>height</em></strong><em>.equalTo(view.snp.width).</em><strong><em>dividedBy</em></strong><em>(2).</em><strong><em>offset</em></strong><em>(-30)</em></pre><p>Here, both <strong>view1</strong>’s height and width attributes are fractionally related to the superview’s width by the same divisor and offset, so we can apply the appropriate constraint to both of them by chaining them together!</p><p>If you ever want to pin a view’s edges to the superview’s, it’d be as simple as calling —</p><pre>make.<strong>leading.trailing.top.bottom</strong>.equalToSuperview()</pre><p>You can even call conveniences like edges to indicate you want to create constraints for all surrounding x and y-axis attributes for a view —</p><pre>make.<strong>edges</strong>.equalToSuperview()</pre><p>You can apply modifications like an offset, inset, or multiple by appending a method call at the end of your constraint declaration, which applies it to any attribute indicated on the left hand side (even chained ones) —</p><pre>make.edges.equaltoSuperview().<strong>inset</strong>(<br>    <strong>UIEdgeInsets</strong>(top: 5, left: 20, bottom: 5, right: 20)<br>)</pre><p>And it goes without saying that translatesAutoresizingMaskIntoConstraints are already accounted for. 😌</p><p>This is just a small subset of the functionality you get out of the box, and if the use case fits your app for those conveniences, I’d recommend giving it a try to see how it can clean up your UI!</p><p>What I love about SnapKit specifically is that you can really get creative with your components. Custom programmatic UI can be a breeze to wire up, and the number of lines you’ll have to debug are a fraction of what an NSLayoutConstraint implementation would take.</p><p>We run the app and see the last example for our even squares 😢 —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*nNab8AT4FSx4kf9tva6pAw.png" /></figure><p>Will you actually <em>need</em> half of the functionality you get from importing this? Probably not.</p><p><em>But why do people buy 1TB iPad Pros just to use Procreate? Why do we opt for new 13&quot; Pros when our 15&quot; MacBooks from a few years ago runs perfectly fine? Why do we get Hulu+ when we know we’re only going to watch maybe 3 channels from it?</em></p><p><strong><em>Because it’s cool.</em></strong></p><p><strong><em>Because it’s fun to have more things.</em></strong></p><p><strong><em>Because no one told me any better when I first started out. </em>💩</strong></p><h3>—</h3><h3>Making decisions 😨</h3><p>I love programmatic layout, whether first party or not. I love how concise it is with the right extensions. I love how you can line break to debug and don’t have to visually diagnose the storyboard when constraints aren’t pinning correctly and so on.</p><ul><li><em>“It’s easier to componentize UI.”</em></li><li><em>“It makes version control way more streamline.”</em></li><li><em>“You get more control and customization out of your UI.”</em></li></ul><p>And while there are grounds for these arguments, after getting the opportunity to dig a little deeper and explore IB, I found there are also plenty of benefits using the IB approach outside of bare code.</p><ul><li><em>The volume of your interface code is seriously cut down.</em></li><li><em>You can leverage XCode’s powerful built in auto layout functionality within Storyboard.</em></li><li><em>You can </em><strong><em>literally see</em></strong><em> what you’re doing to your UI before running the app so runtime errors are significantly mitigated.</em></li></ul><p>The features I’m writing now, which I assumed would take a lot of wrestling in IB, have been pretty stress free to implement. I may still have a personal bias for programmatic layout, but for what it’s worth, even the <a href="https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/AutolayoutPG/ProgrammaticallyCreatingConstraints.html#//apple_ref/doc/uid/TP40010853-CH16-SW1">Apple Documentation</a> states:</p><blockquote>“Whenever possible, use Interface Builder to set your constraints. Interface Builder provides a wide range of tools to visualize, edit, manage, and debug your constraints.” — Tim Cook (probably)</blockquote><p>But their opinion doesn’t matter either. 😬</p><p>At the end of the day, the benefits of code-only or storyboard solutions are all moot when you don’t consider the impact to your codebase, team, or process.</p><p>So to answer the question… <em>It depends.</em></p><p>(I know, but you saw it coming a mile away) 🙃</p><p>As a closing note, for you and me, we shouldn’t dismiss an approach due to predisposed notions without exploring how it’ll fit in our day-to-day, because there’s only one wrong way when it comes to implementing interfaces in Swift…</p><p>…frame-based layouts 🥴</p><p><em>Thanks for reading! I hope y’all are staying safe at this time. If you have any questions, don’t like the article, or just want to say hi — feel free to leave a comment! If you want to dig around, here’s a link to the code:</em></p><p><a href="https://github.com/josh-marasigan/LayoutMediumArticle/tree/master">josh-marasigan/LayoutMediumArticle</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9530a60eedf4" width="1" height="1" alt=""><hr><p><a href="https://uxdesign.cc/the-why-what-and-how-of-swift-auto-layout-9530a60eedf4">The why, what, and how of Swift Auto-Layout</a> was originally published in <a href="https://uxdesign.cc/">UX Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“The Beacons are lit!” — An Observer Design Pattern Guide in Swift]]></title>
            <link>https://codeburst.io/the-beacons-are-lit-an-observer-design-pattern-guide-in-swift-8089bf1310cf?source=rss-57c4402ff511------2</link>
            <guid isPermaLink="false">https://medium.com/p/8089bf1310cf</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Josh Marasigan]]></dc:creator>
            <pubDate>Mon, 30 Apr 2018 03:44:07 GMT</pubDate>
            <atom:updated>2020-06-11T06:05:23.421Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xEfI6sWxnJQuephbu3wfxg.png" /></figure><p>Hey there! Thanks for stopping by. This guide contains snippets of my sample app for the Observer Design Pattern. For any reference or context needed, please follow this link to the GitHub repo:</p><p><a href="https://github.com/josh-marasigan/ObserverDesignExample">josh-marasigan/ObserverDesignExample</a></p><p><strong>[LOTR Disclaimer]</strong></p><p><em>Do you remember that one scene from LOTR: Return of the King? The one where Pippin climbs to the top of Minas Tirith and lights the beacon?</em></p><p><em>The lighting of one beacon starts a chain reaction, with one guard watching the previous beacon in the queue to be lit before lighting his own. Next thing you know, one beacon signals the next, going on and on, until finally the last beacon is set on fire. From one end of Middle Earth to the other, the signal finally reaches Rohan and notifies Théoden that Gondor seeks for aid</em> 🔥</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*mIgcqpp-N7llg06Q7AFgDA.gif" /><figcaption>“The Beacons of Minas Tirith! The Beacons are lit! Gondor calls for aid.”</figcaption></figure><p><em>You’re probably thinking:</em> What does that have to do with the Observer Pattern? And why are you like this?</p><p>First, here’s a rough definition:</p><p><em>The</em><strong><em> Observer Pattern</em></strong><em> consists of objects (called </em><strong><em>Subjects) </em></strong><em>that notifies other objects (called</em><strong><em> Observers) </em></strong><em>that an update/state-change had occurred to it, and if needed, to act accordingly to this change.</em></p><p>In the <strong>Subject</strong> — <strong>Observer </strong>relationship, the Subject isn’t required to know anything about the Observer(s) subscribing/listening to them, and sometimes even vice-versa.</p><p>This promotes a <a href="https://stackoverflow.com/questions/2832017/what-is-the-difference-between-loose-coupling-and-tight-coupling-in-the-object-o">loosely coupled</a> design, as Subjects are solely responsible for notifying, and Observers are solely responsible for listening!</p><p>Like the Guards that light the beacon, Observers are perpetually <em>listening</em> for a change of state to occur on a subscribed subject (in this case, the state of the beacon: lit 🔥 or not lit 💦). Once a state change has happened (ie. the beacon is now on fire), the Observer receives and reacts to this signal.</p><h3>The Observer Pattern in action:</h3><p>We’re going to be making a simple single-view app that changes the contents of its view whenever it’s main button is pressed.</p><p>We’ll have a button (<strong>Subject</strong>) that will be <em>notifying</em> an <strong>Observer </strong>(an arbitrary view containing some labels) of its changes. In order for the UIView to receive notifications from this button, it will have to first <em>subscribe</em> to it.</p><p>To do this, we’ll use the <a href="https://developer.apple.com/documentation/foundation/notifications">Notifications Framework</a> to subscribe objects to one another and send <a href="https://developer.apple.com/documentation/foundation/notification">Notifications</a>/events from one object to the other.</p><p><em>Here’s a visualization on how subscriptions bind these events:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*HprL26UKih0MdmIaY8Amkg.png" /></figure><h3>On the Observer and Receiving Notifications:</h3><p>In order for our Observer to subscribe to this button Subject, it needs to find a way to identify the notification/event it expects to receive.</p><p>Subjects may have multiple observers and different notifications posted, so having a way to uniquely identify a notification will make it so that Observers will only receive notifications of that specific name. This way, they will receive just the events they care about!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d828658d91c034d4e9355744b38ec39/href">https://medium.com/media/1d828658d91c034d4e9355744b38ec39/href</a></iframe><p>Here we have a struct of two unique event names that our button (the Subject) will use to identify the Notification it sends. For example, the Notification Framework will only notify Observers of a Notification named observer-example.teal occurring if (and only if) they are registered for that event with that <em>exact</em> event name.</p><p>So how do we do that?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b18029ca5f9eeea20899d18e961942e/href">https://medium.com/media/9b18029ca5f9eeea20899d18e961942e/href</a></iframe><p>On our init call, we execute a method ( configObservers) that adds four Observers to this UIView’s (TitleAndTextView) instance. We see that our call to the NotificationCenter’s <a href="https://developer.apple.com/documentation/foundation/nsnotificationcenter/1415360-addobserver?language=objc">addObserver</a> method takes four parameters:</p><ol><li>The Object that will now be observing for a notification/event (in this case self / the TitleAndTextView instance)</li><li>The selector that points to the method to be executed once a notification is received by the Observer.</li><li>The unique <strong>name</strong> of the Notification which acts as an identifier so that this Observer will know to solely listen for that specifically named Notification.</li><li>An optional object to be passed from the Subject that sends the Notification for this Observer to receive. The selected handler (see #2) for this Observer may receive an object (of type [<a href="https://developer.apple.com/documentation/swift/anyhashable">AnyHashable</a> : Any]?) from the Subject as a parameter and can be accessed by this object from the Notification object sent. (ie. notification.userInfo)</li></ol><p><strong><em>So what does this mean?</em></strong></p><p>Well from now on, or until these Observers are de-allocated, they will perpetually be listening for the named Notifications they are registered for. (Note that for iOS 9 or later, de-allocation for Observers is taken care for you!)</p><p>Again, every time a Subject sends a Notification, if there is an Observer listening for that Notification (ie. the names match), then the Observer will receive the Notification and execute the method indicated by its selector (with an optional object sent by the Subject).</p><p>We’re missing one more piece for this to make sense (I hope 😅). We still need to have a Subject to actually send these Notifications!</p><h3>On the Subject and Posting Notifications:</h3><p>Our Subject wants to let some sort of Observer know that something has happened to it. Maybe there’s one Observer listening, maybe there’s one hundred, or maybe there’s no one listening at all!</p><p>The point is: <em>the only thing the Subject cares about is to send a Notification indicating that its state has changed.</em></p><p>Think about it like someone making a Facebook post because they just went on a trip or got a new job. <em>Does anyone care?</em> Maybe or maybe not, but the person making the post doesn’t directly tell each of his friends what happened to him. He sends a notification indicating his state as a person has changed, and if you’re one of his good buddies (ie. subscribed to him), you get this notification and react to it (maybe by liking his pictures)</p><p>In our app, we want our button Subject (changeBackgroundButton) to send either a Notification named observer-example.teal or observer-example.pink depending on its current state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20e7778bb6c6ba50172cf7017a76f2a5/href">https://medium.com/media/20e7778bb6c6ba50172cf7017a76f2a5/href</a></iframe><p>Assume a user has pressed our button, changeBackgroundButton, and executes its handler, changeBackgroundButtonAction.</p><p>What happens next? We look for the current state of our Subject (in this case the state of our Subject’s super view: ViewController) and change it.</p><p>If the background state is pink, we change it to teal and vice-versa. We set a constant (notificationIdentifier) to hold the name value of the Notification that we want to send according to this change of state (lines 38–40).</p><p>After this, we need to actually send the Notification (named with our constant’s value) to tell our Observers that something just happened (‼️)</p><p>To do so, we use NotificationCenter’s post method in order to send a Notification with that name to any Observer that cares about it. If an Observer is listening for a Notification with that specific name, it will proceed to execute what it needs to once it receives it. As indicated earlier, you can also pass in objects through the object parameter in this call. (We leave it nil in this case, since we only want to notify the subscribed Observer about the event happening)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*B1knlrAknP06TvfSgmwAcA.gif" /></figure><h3>Run it and take a look at what happens.</h3><p>When we run our sample app, we can see that the button Subject sends a uniquely named Notification for its Observer (the centered view containing the emoji and title) to listen to.</p><p>Once received, the Observers will execute their handling methods accordingly (see how the main label and the emoji toggles!)</p><h3>Cool right? (right?)</h3><p>This can be a pretty useful feature, as objects can now notify each other of state changes without even knowing about one another, from anywhere in the app!</p><p>You won’t have to create a delegate for one class instance to interact with another, keeping communication related changes to these classes at a minimum.</p><h3>So what’s the catch?</h3><p>The Observer Pattern is far from perfect. Think about the case of our example:</p><h4>Possible Performance Issues</h4><p>We have one button Subject that notifies two Observers at any given instance of a user’s interaction (two for a pink state change, two for teal), but what if we had ten observers for that Notification? What about one hundred observers?</p><p>This could leave some significant performance issues if left unattended. Sending one Notification notifies an N number of Observers (depending on your implementation) and gives you a linear upper bound run-time complexity of <em>O(</em><em>N)</em>.</p><p>With a protocol/delegate pattern, a similar update would cost the same complexity as any other method call, giving you a constant run time of <em>O(</em><em>1)</em>.</p><h4>Your Data Flow Might Get Ridiculously Complex</h4><p>When any object in the app can send any Notification to be received at any location by any Observer, you might have a difficult time keeping track.</p><p>If implemented without the complexity of your data flow in mind, the way your objects communicate data and state changes might look a little something like this..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dbjL9SvCRtXsjKZYhbnj8w.jpeg" /></figure><p>So like any design pattern, it’s a tool with its own set of pros and cons, and it’s up to you, the developer, to mitigate the possible consequences of your design choice. 👍</p><p>There’s probably way more reasons on why you should and shouldn’t use the Delegate Pattern outside of what this guide contains (and outside of what I researched), so I’ll leave that for you to look up! 💩</p><p>Don’t forget to check out the GitHub repo linked above for this project! Feel free to pull the repo, run the sample app, and of course, look at the source code in its entirety.</p><p><strong>As always, thanks for reading! 💕</strong></p><h3>Credits:</h3><p>I found the following resources incredibly useful while writing this article so please check them out:</p><ul><li><a href="https://www.youtube.com/watch?v=srqiDnLEocA&amp;t=653s">Sean Allen’s video tutorial</a> on this very topic.</li><li><a href="https://www.raywenderlich.com/160653/design-patterns-ios-using-swift-part-22">Lorenzo Boaro’s</a> article on iOS Design Patterns</li></ul><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8089bf1310cf" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/the-beacons-are-lit-an-observer-design-pattern-guide-in-swift-8089bf1310cf">“The Beacons are lit!” — An Observer Design Pattern Guide in Swift</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Clean your room before I get home!” — A Guide to Swift Delegates]]></title>
            <link>https://codeburst.io/clean-your-room-before-i-get-home-a-guide-to-swift-delegates-4e115c9a7ae9?source=rss-57c4402ff511------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e115c9a7ae9</guid>
            <category><![CDATA[delegation]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Josh Marasigan]]></dc:creator>
            <pubDate>Fri, 15 Dec 2017 05:10:34 GMT</pubDate>
            <atom:updated>2017-12-15T14:29:47.830Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kOBuV3CnhGY7gF07Tk1zCQ.png" /></figure><p>It’s finally summertime. You just got home from your last day of 6th grade and you can’t wait to just lay in bed and play Pokemon Ruby until your eyes hurt (or until you go through that whole pack of AA batteries). Before you even get to your room you get a text from your mom..</p><p><em>“Josh, I’m working late today. Can you please wash the dishes, clean your room, and walk Nala before I get back?”</em></p><p>You look at that text and give a heavy sigh. You were supposed to beat the elite four - but instead you’ve been given a list you have to do before Mom gets back..</p><p>Now think of 6th grade me as a class named as ‘Son’ and my mother as the class ‘Mom’. The Mom class doesn’t want to do these chores at the moment, she is probably busy at work doing other tasks. There’s a chance she doesn’t even have the supplies required to do these chores, but she wants to get the chores done. So what does she do? <strong>She tells another class, the Son class, to do the chores for her</strong>.</p><p>In short:<em> Swift Delegation is a way for a certain class or struct to </em><strong><em>delegate </em></strong><em>tasks to another class or struct</em>.</p><p>Let’s take a look…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbcc5c37c0766e974ec0197c1ce96960/href">https://medium.com/media/fbcc5c37c0766e974ec0197c1ce96960/href</a></iframe><p>Just FYI here’s a little technical definition because I won’t be going in depth on protocols:</p><p><em>A </em><strong><em>protocol </em></strong><em>is a set of methods or properties. When adopted/inherited, these methods or properties </em><strong><em>must </em></strong><em>be implemented by the adopting class (or structure, or enum). </em>For those of you that know Java, it’s very similar to Java Interfaces with a few subtle nuances. (Look them up while Google is still free)</p><p>So with that, we can see that the ‘MomDelegate’ protocol is the list of chores that we want our ‘Mom’ class to delegate/order our ‘Son’ class to do.</p><p>I know what you’re thinking. “What the heck, they’re just function names. They don’t actually <strong>do</strong> anything.” … <em>yet. </em>That’s because these functions need to be implemented first. And who is gonna implement these functions? The ‘Son’ class who is actually going to do the chores…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a3852876bbb4df3d02929fcb117af71/href">https://medium.com/media/7a3852876bbb4df3d02929fcb117af71/href</a></iframe><p>In short: <em>Treat the ‘MomDelegate’ protocol as just a list of chores on a notepad. The ‘Son’ class who is going to be reading the notepad is going to implement/do those chores..</em></p><p>The previously empty function headers are now fully implemented. The ‘Son’ class is now capable of doing all these chores, so when another class tells them what to do, they already have the steps/code ready to execute when the time comes!</p><p>So what does this all mean? To make sense of this, let’s take a look at the last missing piece of the puzzle - The ‘Mom’ class..</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc9c1474f90d4f38b315dacc21bccf44/href">https://medium.com/media/fc9c1474f90d4f38b315dacc21bccf44/href</a></iframe><p>A very important thing to note here:</p><p>The ‘Mom’ class has an instance of a ‘Son’ class, but remember: The ‘Son’ class had conformed to the ‘MomDelegate’ protocol.</p><p>This means that the ‘Son’ is capable of doing these chores, because by implementing ‘MomDelegate’<strong>, the ‘Son’ class assures anyone that he knows what to do when any of the ‘MomDelegate’ chores need to be done</strong>.</p><p>He knows how to wash dishes, how to walk the dog, how to clean his room, he might even know other things we don’t care about that don’t relate to chores! But the point is:<em> By conforming to the ‘MomDelegate’ protocol, we know that the ‘Son’ class is capable of doing anything on that chore list.</em></p><p>So what’s next? We let our ‘Mom’ tell ‘Son’ to do these chores..</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff9b228a0c736ce421d88f0c37e0dd86/href">https://medium.com/media/ff9b228a0c736ce421d88f0c37e0dd86/href</a></iframe><p>We first instantiate our ‘Son’ class and set a constant ‘josh’ as an instance of class ‘Son’. Then we instantiate our ‘Mom’ class and set a constant ‘joshsMom’ while passing our ‘josh’ instance as a parameter. It’s like we’re saying: <strong>‘josh’ is the son of joshsMom</strong>.</p><p>We have to define this relationship because without ‘joshsMom’ owning an instance of ‘josh’, ‘josh’ can’t be told what to do. Imagine ‘joshsMom’ is shouting in an empty room expecting someone to wash their dishes. No one’s there and nobody is going to do it for you. Kinda like how it is at the moment now that I moved to Dallas! (I love you Mom I’ll be visiting soon)</p><p>Finally, when we say ‘joshsMom.tellJoshWhatToDo()’ we are executing all those chores in the ‘tellJoshWhatToDo()’ function through ‘josh’. It’s ‘josh’ himself that does these chores <strong>because the instance ‘josh’ is now the ‘_son’ variable in the ‘Mom’ class</strong>!</p><p>The really cool thing going on here is that ‘joshsMom’ doesn’t need to know how ‘josh’ does these tasks. She just has to tell him what to do. By <em>delegating</em> these chores to ‘josh’, those tasks can be done without ‘joshsMom’ doing any of the work/execution!</p><p>Delegation is a great way to separate your functionality in a need to know basis. Here, only the ‘Son’ class knows how to do those tasks. The ‘Mom’ class doesn’t care how it’s done, <em>as long as it’s done</em>.</p><p>To You Devs: With delegates, we are able to indicate important events that happen in one class and react to them in another. Think of a back button being pressed and a delegate calling a function ‘onBackButtonPress()’ which tells its navigator to pop the current View Controller.</p><p>The View Controller doesn’t care about what the Coordinator does, it just tells it that an action had occurred and for Coordinator to act in response to it.</p><p>To wrap this up: <em>All the cool kids use delegates and you should too! There are some caveats of using delegation, but I’ll let you look that up for now ;)</em></p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e115c9a7ae9" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/clean-your-room-before-i-get-home-a-guide-to-swift-delegates-4e115c9a7ae9">“Clean your room before I get home!” — A Guide to Swift Delegates</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Colorful Guide to Swift Optionals]]></title>
            <link>https://codeburst.io/a-colorful-guide-to-swift-optionals-357c2b92684b?source=rss-57c4402ff511------2</link>
            <guid isPermaLink="false">https://medium.com/p/357c2b92684b</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[optionals]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Josh Marasigan]]></dc:creator>
            <pubDate>Tue, 10 Oct 2017 01:54:38 GMT</pubDate>
            <atom:updated>2018-04-28T17:45:10.407Z</atom:updated>
            <content:encoded><![CDATA[<p>So what in the world does that ‘?’ actually mean in Swift? You see it everywhere from variable declarations to parameters and return values. When I first got started with Swift, seeing that ‘?’ identifier made me go “???”.</p><p>Those variables with ‘?’ marks are <strong>Optional Values</strong>, meaning that any constants or variables with the ‘?’ operator appended at the end of it are <strong>optional </strong>and can be<strong> something OR nothing (nil)</strong>.</p><p>Think of it like a cardboard box you found on top of a shelf. Unfortunately the shelf is really high up and you can’t reach it yet, so you don’t know if that box contains something or it’s just an empty box someone left. (I know, what a jerk right, the recycling bin is like 2 feet away)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-N_Ozzu84KmqrI86NQF2ew.png" /></figure><p>This is a really powerful feature in Swift. You can use optionals to anticipate a ‘nil’ value and still keep your app running by safely unwrapping (more on this later) those values without your compiler throwing up at you. You can also use optionals to anticipate values that are nil at the moment, but later on might not be! Confusing so let’s dig around a bit…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e15cd7886594a8e032bce8c396e1c7f/href">https://medium.com/media/4e15cd7886594a8e032bce8c396e1c7f/href</a></iframe><p>The first variable we cast is of type ‘String?’, and it sounds exactly how it’s typed: “What’s in this thing, a <em>String?</em>”</p><p>This gives the variable ‘box’ the ability to be either a String or nothing at all. In fact, <strong>optional values are the only way for variables to contain nothing/‘nil’</strong> within them. It’s important to note that without being set with a value, optional types are <strong>defaulted </strong>to ‘nil’.</p><p>We see on our second box variable that we cast our variable to type ‘String?’ but we also set it’s contents. This means that later when we actually use these variables, the first box will be of value nil and the second box will be of value “Something”…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1689654b099b89ac610e77c89b401a80/href">https://medium.com/media/1689654b099b89ac610e77c89b401a80/href</a></iframe><p>That’s pretty cool right? You might be wondering why that print statement on the second box had an “Optional(“Something”)” output. “What the heck Josh, I’m even more confused now!”. Well no worries, cause now we’re going to get into safely using optionals in our code and getting rid of that weirdness going on!</p><h3><strong>Unwrapping Optional Values</strong></h3><p>That Optional key word your console spits at you around the “Something” string value actually means that the box is still of type (String) Optional!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*pzz7H16PsPgL1CK4aC0ybA.png" /></figure><p>Like the picture depicted, the box variable isn’t the string value “Something”, it’s actually <strong>the box which happens to contain “Something”</strong>. So what does that mean? It means we have to <strong>take the something out of the box </strong>so we can use it. Here are three ways to <strong>unwrap</strong> the contents of your variable so you can use it for all sorts of shenanigans.</p><h4><strong>Force Unwrapping</strong></h4><p>The first way is to just straight up tear the box apart. You don’t care if there’s something or nothing in it, you just want to open the box like a madman. To force unwrap an optional variable, simply add the “!” indicator at the end of it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f724bd8ec91962a0f48ed14f02937d70/href">https://medium.com/media/f724bd8ec91962a0f48ed14f02937d70/href</a></iframe><p>Here you’re telling your compiler: “Hey! I don’t know if there’s something in this box, but you better give me something when I open it or else!”. Let’s take a look on how this works…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/177a4b5940f87d4a0b2b3a1b4233d299/href">https://medium.com/media/177a4b5940f87d4a0b2b3a1b4233d299/href</a></iframe><p>The first case we actually set a value for the box. So when we rudely tell our box to force unwrap (!) itself, it’ll tear the cardboard apart and leave you with just it’s contents. You got rid of the box, and now it will contain just “Something”. (Removing that Optional() indicator when printed)</p><p>Let’s take a look at the second case. Variable box is <strong>not</strong> set to a value, but we force unwrap it anyways…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*_aq92yF23Xc2nio3xb_vRA.png" /></figure><p>There’s nothing in the box! The compiler throws up on you with a fatal error and you have to pack it up and get a new gig because my mom was right I should’ve done nursing! How did this happen? Well when you printed out ‘box!’ you ended up attempting to print a nil value. You told your compiler you <em>for sure</em> had a value for variable box but never set it.</p><p>It’s not a sin to force unwrap things though! In some cases where you <strong>need</strong> to have values for variables and you’re uncertain if they’ll be there or not, you can use force unwraps to make sure your app doesn’t run without these values. (For example, a View Model for a View Controller)</p><h3><strong>If lets And Guard Lets</strong></h3><p>The other two, and much safer, ways to unwrap optional values are if-lets and guard-lets. Pictures can’t really do them justice, so lets just take a look at how they’re used, starting with if-lets...</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3f516e0b42b2ad417dfbb13f5792424/href">https://medium.com/media/c3f516e0b42b2ad417dfbb13f5792424/href</a></iframe><p>Our syntax for if lets follow:</p><p><strong>if</strong> the contents for our optional variable is not nil, then <strong>let</strong> the variable<strong> boxContents </strong>equal (<strong>=</strong>) to those contents of <strong>box</strong>, following the closure where you can freely use the variable boxContents (<strong>{}</strong>).</p><p>You’re saying, “Hey, if this value is not nil, I get to use it within this closure!”</p><p>You may now use boxContents in this closure and treat it as a String, since boxContents is the actual value within the box! If box was nil, it would have never passed your if condition in the first place.</p><p>It’s important to note that the scope of your unwrapped variable will only be contained within this closure, meaning you cannot use ‘boxContents’ outside of your brackets {}. To use unwrapped values outside of this closure, we have to use something a little different…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0785d6cf8abf84b360669ca52d76d8e9/href">https://medium.com/media/0785d6cf8abf84b360669ca52d76d8e9/href</a></iframe><p>Here we are using a guard let. Guard lets are similar to if lets, but the main feature discerning the two is that guard lets deal with the case that your optional value is nil right then and there.</p><p>The closure following your guard let is preceded by an ‘else’, so you’re saying “Hey, I’m gonna unwrap this value, but if it’s nil, then I’m gonna deal with this right now!”</p><p>This is different from an if-let, because now you can use that unwrapped value <strong>anywhere</strong> within the scope of your function, meaning it has the same scope as box. A caveat of this is that the closure following the ‘else’ of a guard let <strong>must escape</strong>, meaning if you are calling it within a function, you must return in the case that value is nil, or if within a conditional loop (like for or while), you must break or continue.</p><p>Guard lets are great in ensuring optional values from parameters have non nil values prior to calling anything that might require them, and when placed as the first things within your function, can be a great way to keep your code concise and structured.</p><p>Wow! Look at you now. You’ve learned what optionals are and even have three ways to deal with them! If you need any more resources on optional values and unwrapping, the Apple documentation is a great resource. Or just google them. It’s 2017, seriously.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=357c2b92684b" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/a-colorful-guide-to-swift-optionals-357c2b92684b">A Colorful Guide to Swift Optionals</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>