<?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 Eric Downey on Medium]]></title>
        <description><![CDATA[Stories by Eric Downey on Medium]]></description>
        <link>https://medium.com/@edowney271?source=rss-10e4cc1e9cdc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6yX7f5sm_bA9nYg8cp0pxg.jpeg</url>
            <title>Stories by Eric Downey on Medium</title>
            <link>https://medium.com/@edowney271?source=rss-10e4cc1e9cdc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 07:39:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@edowney271/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[Extensions on Optional Types]]></title>
            <link>https://medium.com/swift2go/extensions-on-optional-types-cc0374a4ead4?source=rss-10e4cc1e9cdc------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc0374a4ead4</guid>
            <category><![CDATA[swift-extensions]]></category>
            <category><![CDATA[optionals]]></category>
            <category><![CDATA[swift-playgrounds]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Eric Downey]]></dc:creator>
            <pubDate>Sun, 26 Aug 2018 18:39:29 GMT</pubDate>
            <atom:updated>2018-08-27T06:57:53.043Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0cmKOEHuXAreJ9vR" /><figcaption>Photo by <a href="https://unsplash.com/@emilymorter?utm_source=medium&amp;utm_medium=referral">Emily Morter</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hey everyone! I wanted to write this quick article because I love using this technique and it’s not the most obvious implementation. So, if you’ve worked in Swift for more than 2 minutes, then you’ve probably seen <em>Optional</em>s. There are great articles explaining what these things are and how to work with them. I am not going to get into that here. What I want to talk about is the dreaded</p><pre>Expression implicitly coerced from ‘String?’ to ‘Any’</pre><p>error that you get every time you try to print an <em>Optional</em>. Okay, so it’s not the most important use case in the world, but without it, your code would either be littered with warnings, or you would have to cast everything to an Any type every time you did this. So the following implementation:</p><pre>let val: String? = nil<br>//…<br>print(val) // Warning is generated here</pre><p>would become</p><pre>let val: String? = nil<br>//…<br>print(val as Any)</pre><p>and if you have lots of these or if the type of <strong>val</strong> changes, this can become a nightmare to maintain. So, what is the elegant fix because it definitely is not using String(describing: val), which is the suggested fix in Xcode. I’m so glad you asked 😁. To fix this, let’s write an extension on the Optional type and yes that is completely possible and really cool! Let’s start by writing the following:</p><pre>extension Optional where Wrapped == String {</pre><pre>}</pre><p>In the previous code block, we are extending the Optional type where the Wrapped type is a String. The Wrapped property is the identifier for the generic type that is declared with the Optional declaration (<a href="https://docs.swift.org/swift-book/LanguageGuide/Generics.html">Swift Generics</a>). That means whatever code we write in this extension will only be available to optional string types (String?). So let’s implement our extension. In the next code block we are going to add a new property called valueOrEmpty. Here is the code:</p><pre>extension Optional where Wrapped == String {<br>    var valueOrEmpty: String {<br>        guard let unwrapped = self else {<br>            return “”<br>        }<br>        return unwrapped<br>    }<br>}</pre><p>First, we unwrap the optional in a <strong>guard</strong>, same as any other optional. Then if the value exists, we return it, otherwise, we return an empty string. Now, how does this affect the code from earlier? Instead of casting to an Any type, we would now have the following:</p><pre>let val: String? = nil<br>//…<br>print(val.valueOrEmpty)</pre><p>This allows us to turn an optional string into a non-optional string where the string will either have a value or it will be empty. As you can tell, this can be applied to lots of things other than just strings and printing out values.</p><p>I’ve gotten tripped up multiple times when I want to compare two booleans values where one or both are optional Bools. We can create an extension that gives us false if the value is nil. This is most likely a safe assumption because if the value of a bool is nil, we want the failure case of an <strong>if</strong> or <strong>guard</strong> statement to execute. And that brings me to my final point.</p><blockquote>With Great Power, Comes Great Responsibility</blockquote><p>This can be used for all kinds of things, you could go nuts with it. But remember, optionals are actually a really great thing in our code. When I’ve worked with other languages and I unexpectedly get a null pointer exception, I want to tear my hair out because there are no optionals (looking at you Java, you know what you did). <strong>This should not be used to get around all optionals</strong>. There are plenty of cases where optionals are necessary and good.</p><p>Alright, now that my PSA is over, hopefully this quick article revealed some cool extensions you can write in your code. Thank you for reading! 😁</p><h4>Github</h4><ul><li><a href="https://gist.github.com/Ericdowney/59d33f53677bbe9ef11227716b1b03b3">https://gist.github.com/Ericdowney/59d33f53677bbe9ef11227716b1b03b3</a></li></ul><h4>Versions</h4><ul><li>Xcode 10 beta 6 — Playground</li><li>Swift 4.2</li></ul><h4>References</h4><ul><li><a href="https://docs.swift.org/swift-book/LanguageGuide/Generics.html">https://docs.swift.org/swift-book/LanguageGuide/Generics.html</a></li></ul><figure><a href="http://bit.ly/2KkkwGL"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5-oC2BqqizoRxIls08WMmA.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc0374a4ead4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift2go/extensions-on-optional-types-cc0374a4ead4">Extensions on Optional Types</a> was originally published in <a href="https://medium.com/swift2go">Swift2Go</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forms in iOS — Part 1]]></title>
            <link>https://medium.com/swift2go/forms-in-ios-part-1-395267a764e?source=rss-10e4cc1e9cdc------2</link>
            <guid isPermaLink="false">https://medium.com/p/395267a764e</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[forms]]></category>
            <category><![CDATA[storyboard]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Eric Downey]]></dc:creator>
            <pubDate>Mon, 20 Aug 2018 15:35:13 GMT</pubDate>
            <atom:updated>2018-08-21T22:39:45.721Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9TOW_17_3yQQny_kbIDYDw.jpeg" /></figure><p>Hello everyone! This is my first medium article so feedback is very much appreciated. Today, we are going to look at using the <em>Object </em>reference in Xcode Storyboards. Since I always love real world use cases, the bulk of this article is going to examine how to implement Forms using these <em>Object </em>references. By the end of this article the goal is to have highly reusable form components that can be configured via Storyboards. This is also just part 1. In this part we are going to build a simple form example and in the second article we will examine a more complex example.</p><h4>Object References</h4><p>Alright, so what are <em>Object </em>references in Storyboards? You’ve probably seen the <em>Object </em>reference in the UI Library in Xcode (It’s the little yellow cube show in Figure 1). Back in the olden days of iOS dev this object used to be used for the File’s Owner reference in Nib files. If that doesn’t make any sense, don’t worry about it. We live in much better times now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*W9gh-Ra4hvYWMx5SkLfV_w.png" /><figcaption>Figure 1 — Object Reference from Xcode’s UI Library</figcaption></figure><p>Now from what I’ve seen, it’s not used very much today. I know up until recently I never used it. So what can it do? The description in Figure 1.0 kinda says it all. These objects can be used to model anything that inherits from the <em>NSObject </em>class. You can attach <strong>N </strong>number of these things to view controllers in your storyboard. Then you can override their class from the default <em>NSObject</em>. Which is really cool! I can attach a bunch of dependencies to my view controller through the Storyboard. You then setup <em>IBOutlet</em>s on your view controller to create references to these objects and the Storyboard will handle instantiating all of these objects.</p><p>Now you might be thinking that’s cool and all but couldn’t I just add those dependencies to my view controller without the outlets... Of course you can. However, the power of using the Storyboards means any dependencies of these objects can be configured through the Storyboard as well. The Storyboard will handle instantiating all of these objects for us and we don’t have to worry about it. The objects can also reference elements on the view through IBOutlets. We will see how this helps us next when we are implementing the forms.</p><h4>Form Objects in Storyboards</h4><p>This section is going to walk through building a sample Xcode project for our forms example. Feel free to follow along or if you would like to just read, there is a link to the project on my Github at the end of this article. Let’s start with our simple example. Figure 2 has the storyboard configuration for our form. There are two view controllers, one with a button that navigates to the second view controller all embedded in a navigation controller. This will allow us to create more links later on in part 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SiFmCmTsH0besHlEknLVjg.png" /><figcaption>Figure 2— Storyboard Setup for Simple Form Example</figcaption></figure><p>The second view controller contains our form. This form is just three labels and three text fields all embedded in <em>UIStackView</em>s. There is also a submit button at the bottom that will print out the values of the forms.</p><p>Okay. Let’s get to coding. First, create a new group called Forms in the Xcode project. Then create two new files called Form.swift and FormControl.swift as shown in Figure 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*lGJbcqs0QoR-yvswS53k4A.png" /><figcaption>Figure 3 — Form Group Setup</figcaption></figure><p>We are going to start with the FormControl.swift file. This file is going to contain the following protocol:</p><pre><strong>@objc</strong> <strong>protocol</strong> FormControl {<br>    <strong>var</strong> key: String? { <strong>get</strong> }<br><strong>    var</strong> text: String? { <strong>get</strong> }</pre><pre><strong>    func</strong> clear()<br>}</pre><p>This protocol will be what represents our field controls on each of our forms. The <strong>key</strong> is to identify the control, <strong>text</strong> is the value, and <strong>clear</strong> is to reset the value. Now, you’ll notice this protocol is defined with the @objc tag. This will be important in our next code block.</p><pre><strong>class</strong> Form: NSObject {</pre><pre><strong>    @IBOutlet</strong> <strong>var</strong> controls: [FormControl]?</pre><pre><strong>    subscript</strong>(<strong>_</strong> key: String) -&gt; String? {<br>        <strong>return</strong> value(for: key)<br>    }</pre><pre><strong>    func</strong> value(for key: String) -&gt; String? {<br>        <strong>return</strong> controls?.first(where: { $0.key == key })?.text<br>    }</pre><pre><strong>    func</strong> clear() {<br>        controls?.forEach { $0.clear() }<br>    }<br>}</pre><p>The previous code block contains the actual Form class. There a bit of code here, so let’s go through it.</p><ol><li>First is the most important part. The IBOutlet referencing an array of FormControl s. This allows us to configure our form object on the Storyboard to have <strong>N</strong> number of form controls (Text Fields). This is also why the protocol requires the @objc attribute. If the protocol is going to be referenced within the Storyboard, it must have this attribute.</li><li>Second is a subscript method to get values from each control field as follows: form[&quot;controlName&quot;]</li><li>Third is just a function version of our subscript method.</li><li>Fourth is the form clear method.</li></ol><p>The next file to create and class to implement is going to be the subclass of UITextField . Let’s put this file in our <em>Forms</em> group in Xcode. Here is the implementation:</p><pre><strong>@IBDesignable</strong> <strong>class</strong> TextField: UITextField {</pre><pre><strong>    @IBInspectable</strong> <strong>var</strong> key: String?<br>}</pre><pre><strong>extension</strong> TextField: FormControl {<br>    <strong>func</strong> clear() {<br>        text = <strong>nil<br>    </strong>}<br>}</pre><p>In the previous code block I declared the <strong>TextField</strong> class as @IBDesignable to allow the <strong>key</strong> property to be configured via the Storyboard. Then the class conforms to the FormControl protocol via an extension (I usually implement all of my protocol conformance through extensions). Since the UITextField class already has an optional text property, we don’t need to declare the text property. Lastly let’s implement the simple form view controller:</p><pre><strong>final</strong> <strong>class</strong> SimpleFormViewController: UIViewController {</pre><pre><strong>    @IBOutlet</strong> <strong>var</strong> form: Form!<br>    <br>    <strong>@IBAction</strong> <strong>func</strong> submit() {<br>        print(&quot;Form Data:&quot;,<br>            form[&quot;firstName&quot;],<br>            form[&quot;lastName&quot;],<br>            form[&quot;age&quot;])<br>    }<br>}</pre><p>And this is it for the view controller. The IBOutlet references our form and the submit button will just print out the values from our form. Simple right! Alright, maybe not the simplest thing in the world, but from here on out, implementing forms should be easy. Let’s hop back over to our Storyboard to finish the configuration for the simple form.</p><p>First, change all the UITextField s to TextField s. Then drag one of the <em>Object </em>references to our view controller. You can see the object added to your view controller in the top bar of the interface as shown in Figure 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*IDXNkEKEZoFgEekaQk50xA.png" /><figcaption>Figure 4 — Form object reference on the SimpleFormViewController</figcaption></figure><p>Then we want to change the class of the object reference to a Form object as shown in Figure 5. Once the object is a Form connect the IBOutlet form property to this object in the Storyboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*wVMmN1-m17xp7NF_knZpAg.png" /><figcaption>Figure 5 — Form Attributes</figcaption></figure><p>Then move over to the <em>Outlets</em> inspector for the Form and connect all the text fields to the <em>controls</em> outlet collection in Figure 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*mMNOlNXDRBeq3Hg4KKn-Mg.png" /><figcaption>Figure 6 — Form references to TextField controls</figcaption></figure><p>The last thing to configure is to add the keys to each text field. Make sure each text field is configured with the correct key as follows:</p><ul><li>firstName</li><li>lastName</li><li>age</li></ul><p>These keys will be how we extract each value from our form and we actually already handled this in the <strong>submit</strong> action in our view controller. Add the IBAction reference to the submit button in the Storyboard.</p><p>And now everything should be ready to go. Whew! That’s a lot steps, but we made it. Build and run, navigate to the simple form, enter some data, and we should get the following output:</p><pre><strong>Form Data: Optional(&quot;Eric&quot;) Optional(&quot;Downey&quot;) Optional(&quot;27&quot;)</strong></pre><p>Not the best output (thanks a lot optionals), but you get the idea. This is awesome because we can now have as many forms as we want and our view controllers don’t need to re-implement any form logic. 👍</p><p>Even though this is just the simple example, hopefully you can see the power of this design. If you have a lot of forms in your app, it should be really easy to configure your forms in your Storyboard and extract the data. In the next part to <strong>Forms in iOS</strong>, we are going to expand this implementation to include form validation. Thank you for reading my first article here on medium. 😁 Any feedback is welcome and much appreciated!</p><h4><strong>Github</strong></h4><p><a href="https://github.com/Ericdowney/iOSFormExample/tree/article/part1">https://github.com/Ericdowney/iOSFormExample/tree/article/part1</a></p><h4>Versions</h4><ul><li>Xcode 10 Beta 6</li><li>iOS 12 Beta 8</li><li>Swift 4.2</li></ul><figure><a href="http://bit.ly/2KkkwGL"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5-oC2BqqizoRxIls08WMmA.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=395267a764e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift2go/forms-in-ios-part-1-395267a764e">Forms in iOS — Part 1</a> was originally published in <a href="https://medium.com/swift2go">Swift2Go</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>