<?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 Michael Ginn on Medium]]></title>
        <description><![CDATA[Stories by Michael Ginn on Medium]]></description>
        <link>https://medium.com/@michael-ginn?source=rss-4929fc022c0a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TTC7J99vMeWJC88TZZ67zA.jpeg</url>
            <title>Stories by Michael Ginn on Medium</title>
            <link>https://medium.com/@michael-ginn?source=rss-4929fc022c0a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 16:29:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@michael-ginn/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[Creating Optional @ViewBuilder Parameters in SwiftUI Views]]></title>
            <link>https://michael-ginn.medium.com/creating-optional-viewbuilder-parameters-in-swiftui-views-a0d4e3e1a0ae?source=rss-4929fc022c0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0d4e3e1a0ae</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Michael Ginn]]></dc:creator>
            <pubDate>Tue, 27 Oct 2020 21:48:46 GMT</pubDate>
            <atom:updated>2020-10-27T22:11:53.436Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q4rxRoOhMlfpQ5PWfNy_zQ.png" /></figure><p>SwiftUI allows the creation of very powerful custom views that take @ViewBuilder closures, allowing you to nest views inside other views.</p><p>For example, let’s design a Card view that allows you to pass content to be shown on a styled view.</p><p>Here’s the basic card:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/647cbb061e5ae6d1369830fb8a62b58a/href">https://medium.com/media/647cbb061e5ae6d1369830fb8a62b58a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*mi3SPIPERcw91ji3_tDa5A.png" /><figcaption>Our card view</figcaption></figure><p>To allow someone using our view to pass their own content, we can give the view a generic parameter conforming to View, and use the @ViewBuilder modifier to allow them to pass in a @ViewBuilder closure.</p><blockquote>@ViewBuilder is a function attribute that allows you to write a closure in DSL-like syntax that returns a View.</blockquote><p>Here’s our updated code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a04a1b691f724cdf96f541b214be993/href">https://medium.com/media/1a04a1b691f724cdf96f541b214be993/href</a></iframe><p>Why do we use a closure in #3, rather than just a parameter of type Content? It allows us to use the convenient @ViewBuilder syntax when creating a Card. Thus, we can do:</p><pre>Card {<br>  HStack {<br>    Text(&quot;Hello&quot;)<br>    Image(systemName: &quot;face.smiling&quot;)<br>  }<br>}</pre><p>Instead of:</p><pre>Card(content: <br>  HStack {<br>    Text(&quot;Hello&quot;)<br>    Image(systemName: &quot;face.smiling&quot;)<br>  }<br>)</pre><p>Our code above looks very similar, except now we can change what’s in the card just by changing the closure in previews.</p><p>So we’ve seen how easy it is to let your view take a custom @ViewBuilder closure.</p><h3>But what if we want it to be optional?</h3><p>What if we want the option to make a blank card, without making a brand new struct? First, we might try making the closure optional:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*n5A8TKaTvlICFl2uZUOI-w.png" /></figure><p>Unfortunately, you can’t apply @ViewBuilder to an optional type. What if we try to take a closure of type () -&gt; Content? ? This works alright:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b640f10633b12238b8e62611508e831/href">https://medium.com/media/9b640f10633b12238b8e62611508e831/href</a></iframe><p>However, it has a few downsides. One, we have to use the awkward syntax seen in line 24, which looks very weird. Second (and this might be a bug), it seems to break the preview in my instance of Xcode. Third, if we want to provide a default value if content is nil, we’ll have to write some redundant if statement in our body.</p><h3>A better way</h3><p>Ideally, we want to be able to write a constructor like Card() , that automatically fills in the Content type with something appropriate.</p><p>There’s a much better way to do this, and it matches Apple’s declaration. We’ll use an <strong>extension with generic where clause</strong> (simpler than it sounds). Basically, we create an extension providing an alternative init method, but only provide the extension for a certain generic constraint.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fa1e7391ec05267076e340a607ac295/href">https://medium.com/media/9fa1e7391ec05267076e340a607ac295/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WlMjsgzNyn-SyT-bxg5ozA.png" /><figcaption>A beautiful empty card</figcaption></figure><p>This allows us to create elegant initializers for our views, similar to how Button can take either a @ViewBuilder or just a String.</p><h3>Making it even more elegant</h3><p>However, we can go one step further. With Swift 5.3, proposal <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0267-where-on-contextually-generic.md">SE-0267</a> allows us to write functions with where clauses for generic types.</p><p>That means we can simplify the implementation shown above to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59eb0f60c0dfc566b5fdbde80a1741b0/href">https://medium.com/media/59eb0f60c0dfc566b5fdbde80a1741b0/href</a></iframe><p>This works great, and lets us keep all our inits together! Here, we only wrote one alternative constructor, but you could certainly write more, such as a constructor that takes a string and makes Content a Text view.</p><h3>Conclusion</h3><p>We’ve seen how to easily write custom View structs that act as “containers”, taking @ViewBuilder closures and displaying their result. We’ve also solved the problem of writing elegant constructors when a @ViewBuilder should be optional. Hopefully, you find this useful in writing powerful and beautiful custom views!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0d4e3e1a0ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My SwiftUI wishlist for WWDC 2020 (and what I’m doing meanwhile)]]></title>
            <link>https://medium.com/macoclock/my-swiftui-wishlist-for-wwdc-2020-and-what-im-doing-meanwhile-9c7e488155b6?source=rss-4929fc022c0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c7e488155b6</guid>
            <category><![CDATA[wwdc]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Michael Ginn]]></dc:creator>
            <pubDate>Wed, 03 Jun 2020 20:35:24 GMT</pubDate>
            <atom:updated>2020-06-08T05:20:02.173Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*56cYRLHItKvMDB5UYRai2g.png" /></figure><p>SwiftUI is Apple’s brand-new, bleeding-edge declarative UI framework. It’s the first official alternative to UIKit since Apple first let developers make iPhone apps. It seems to be the direction Apple (and the rest of the industry) is headed.</p><p>But, as of its first release, SwiftUI is pretty rough around the edges. The documentation is lacking (practically nonexistent), bugs are everywhere, and compared to UIKit, there’s a lot of functionality missing.</p><p>However, with WWDC 2020 right around the corner, I anticipate big changes and improvments. Here’s a list of features, fixes, and bugs I hope are addressed, and also what my solution for each has been in the meantime.</p><p>For context, I’ve been attempting to use it to rewrite my startup’s production app (which is currently in React Native). The app is a platform for volunteers to find service/activism projects to join and help with.</p><h3>1. Big TabView fixes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*6Ossa1Iaj89Bsj_7G2bm8w.png" /><figcaption>An example tab bar</figcaption></figure><p>SwiftUI comes with a declarative TabView that looks pretty much like your standard, wild-type tab bar. However, when you dive into it, a lot of limitations and unexpected behavior arises.</p><p>The first thing I noticed is that when switching between tabs, state such as navigation position, scroll view offset, etc, are not preserved. In fact, every time you open a new tab, the entire view is re-rendered. This is a big UX issue, since users expect that when they switch tabs, the page will look just how they left it when they come back.</p><h4>How did I fix it?</h4><p>I’ve seen solutions for preserving scroll view offset or navigation state. But for an app as complex as the one I’m building, with many subpages and possible navigation routes, that’s simply out of the question. Instead, modifying code from <a href="https://gist.github.com/Amzd/2eb5b941865e8c5cccf149e6e07c8810">https://gist.github.com/Amzd/2eb5b941865e8c5cccf149e6e07c8810</a>, I used a UIViewControllerRepresentable to wrap a UIKit tab bar controller. This solved the problem of saving state between tabs, but there were more issues.</p><p>First, I noticed that tapping the bar item doesn’t return you to the root, nor does it scroll up. I (kind of) fixed this by designing a custom protocol, RootView, which is a View but with an additional popToTop() method. I also made a type-eraser (see below) to copy the functionality of AnyView</p><pre>public protocol RootView : View {<br>  /// Returns to the top of a navigation stack<br>  func popToTop()<br>}</pre><pre>/// Erases a `View` type, like `AnyView`, but only for views which conform to `RootView`.<br>///<br>/// `RootView` requires views to have a `popToTop` method.<br>public struct AnyRootView : RootView {</pre><pre>  // Conformance to View protocol<br>  public var body: some View {<br>    return eraser<br>  }</pre><pre>  // Erase `RootView` type to `AnyView`<br>  private var eraser: AnyView</pre><pre>  public init&lt;V&gt;(_ view: V) where V : RootView <br>    self.internalPopToTop = view.popToTop<br>    eraser = AnyView(view)<br>  }</pre><pre>  // Although the type of the `RootView` is erased, we need to hold on to the pop to top method so we can provide it to the RootView protocol</pre><pre>  private var internalPopToTop: ()-&gt;Void</pre><pre>  public func popToTop() {<br>    internalPopToTop()<br>  }</pre><pre>}</pre><p>Then, I made the HostingController take AnyRootView instead of AnyView , and made all my root view structs implement RootView . In their popToTop methods, I set all the navigation links on that level to be disabled.</p><p>This works, but it’s very messy and a pain to implement for something that’s standard behavior. I really hope that with this WWDC, Apple has vastly expanded the built in tab bar, so I can use it without issue.</p><h3>2. “if let” support</h3><p>The if let syntax is one of the most distinct features of the Swift language, and provides the most common strategy for dealing with optionals. Probably the most common advice developers will give newbies is to stop using force-unwraps–it’s something that’s ingrained in my head.</p><p>So we expect that in SwiftUI, we could do something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*6Wtz5y0IfE1xTfPLCdBfsQ.png" /></figure><p>But no, we get the error</p><blockquote>Closure containing control flow statement cannot be used with function builder ‘ViewBuilder’</blockquote><p>This is because although our code between the two curly braces looks like a closure, it’s not (see this <a href="https://medium.com/@carson.katri/create-your-first-function-builder-in-5-minutes-b4a717390671">link</a>). It gets converted into a call to the methods of the ViewBuilder class, with the things we put in as arguments. That means that we can only include things that ViewBuilder can deal with; if statements are supported, if let is not.</p><p>If this isn’t something introduced at WWDC, I will be very surprised. if let is such an integral part of Swift, and there are so many applications, that it seems inevitable.</p><p><strong>In the meantime, </strong>there’s a few options. The first is to use map as suggested in this <a href="https://ericasadun.com/2019/06/20/swiftui-handling-optionals/">post</a>. That looks something like:</p><pre>var body: some View {<br>  VStack{<br>    string.map { Text($0) }<br>  }<br>}</pre><p>It works fine, but it’s not perfect. First, it’s not very readable. It’s not obvious that the actual result is Text? and SwiftUI supports optionals in the builder block. Second, Xcode’s autocomplete doesn’t really work that well, so if you’re dealing with anything more complex than a basic data type, you lose the convenience of autocomplete.</p><p>The other option, which hurts me to type but has been my preferred method, is to use “if _ == nil” and force-unwraps. That looks like:</p><pre>VStack{<br>  if string == nil {<br>    Text(string!)<br>  }<br>}</pre><p>My justification is that as soon as if let is supported, I will switch my statements easily to use that. Either way for now is okay, but neither is perfect.</p><h3>3. Lifecycle events in navigation</h3><p>As I’ve grown as a developer, one of the things I started to care about is optimizing memory usage. My app stores a lot of things in RAM, between cached images, my redux-style store of projects, and various state. As a result, I noticed my memory usage was getting worryingly high.</p><p>Here’s where SwiftUI comes in. I realized part of the issue was that objects relevant to a single project were never being de-allocated. This is because when you create a NavigationLink , the destination, and any associated ObservedObjects, are created, before you ever tap the navigation link. On the plus side, this makes navigation fast and responsive, but it also meant I was storing way more than I needed.</p><p><strong>My partial solution</strong></p><p>To solve this, I tried to move most of the heavy lifting into an onAppear modifier for the detail view. That way, information such as comments and team members, which made up the majority of the data, wasn’t loaded until the project page (which had links to the comments page and members page) appeared. This worked fine for lazy-loading this information, but I also wanted to remove the information when the project page wasn’t shown.</p><p>Naturally, I tried using onDisappear . The issue is that onDisappear is called both when you navigate back to the root, but also when you navigate forward to a detail view, and my detail views needed the data I had just de-allocated. So that didn’t work.</p><p><strong>A real solution</strong></p><p>What would really be ideal is if Apple exposed modifiers relating to navigation events. I’m not entirely sure how navigation is handled in SwiftUI (as opposed to UIKit), but some sort of .onNavigationPush and .onNavigationPop would be very appreciated.</p><h3>4. A greatly expanded view library</h3><p>This is the obvious one. There are so many views, including ones which are trivial to port, that exist in UIKit but not in SwiftUI. While wrapping them in a UIViewRepresentable isn’t particularly difficult, it is a bit irritating to have a large number of these files that could very easily be built in.</p><p>Here’s just a few of the UIKit views I have ported:</p><ul><li>Activity Indicator</li><li>Sign in with Apple Button</li><li>UIVisualEffectView</li><li>The share sheet</li><li>WKWebView</li></ul><p>and many others as needed.</p><p>Additionally, there is a ton of expansion that can be done in the existing SwiftUI views. Just off the top of my head,</p><ul><li>Multiline text fields</li><li>Cursor management in text fields</li><li>Some sort of wrap-around stack like CSS’s flex-wrap</li><li>List customization: remove dividers, change the chevron, pull to refresh, etc</li><li>Large navigation titles with a view on the right (like in Messages)</li><li>Scroll view with a binding for position</li><li>Full-screen modals</li><li>Keyboard avoidance</li></ul><p>For SwiftUI to truly become a full-fledged alternative to UIKit, features like these must be added. For now, I’m using a lot of UIKit and various work-arounds.</p><h3>5. And finally, bug fixes!</h3><p>The other biggest issue with using SwiftUI for a production app right now is the myriad of bugs you may encounter. Some of mine:</p><ul><li>Scroll views with a background and navigation bar don’t play nice</li><li>Multiline text can often mess up the rest of the layout unless you use .fixedSize(width: false, height: true)</li><li>Sometimes opening a modal makes the scroll view jump around</li><li>and many, many editor crashes</li></ul><p>This is a first-gen framework, so I expect some bugs, but moving forward, I hope these are things that are addressed.</p><p>That pretty much wraps up my biggest wishes for SwiftUI 2.0. I’m excited for what WWDC 2020 and the future of SwiftUI will bring.</p><p>Do you have other things on your wishlist? Are there obvious solutions to my problems that I missed? If so, feel free to roast me in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c7e488155b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/macoclock/my-swiftui-wishlist-for-wwdc-2020-and-what-im-doing-meanwhile-9c7e488155b6">My SwiftUI wishlist for WWDC 2020 (and what I’m doing meanwhile)</a> was originally published in <a href="https://medium.com/macoclock">Mac O’Clock</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>