<?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 Jianyuan Chen on Medium]]></title>
        <description><![CDATA[Stories by Jianyuan Chen on Medium]]></description>
        <link>https://medium.com/@jianyuan-chen?source=rss-91648a57c5fc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Tq_BZTtkUXUulu8Lbq_mwQ.jpeg</url>
            <title>Stories by Jianyuan Chen on Medium</title>
            <link>https://medium.com/@jianyuan-chen?source=rss-91648a57c5fc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:02:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jianyuan-chen/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[SwiftUI Behind The Scene]]></title>
            <link>https://medium.com/4-minute-swift/swiftui-behind-the-scene-455c9ee17235?source=rss-91648a57c5fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/455c9ee17235</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[apple-wwdc-2021]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Jianyuan Chen]]></dc:creator>
            <pubDate>Wed, 16 Jun 2021 19:37:07 GMT</pubDate>
            <atom:updated>2021-06-16T19:38:01.641Z</atom:updated>
            <content:encoded><![CDATA[<h4>Key Concepts To Help You Understand How SwiftUI Works Behind The Scene</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GHGYpSuEVPRxmSOJI0PxPg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jakobowens1?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jakob Owens</a> on <a href="https://unsplash.com/s/photos/behind-the-scene?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>When I first learned SwiftUI, I was amazed by how much is done automatically for us by SwiftUI. For example, I no longer have to write custom UIView.animateWithDurations remember to make constraint changes outside and call view.layoutIfNeeded inside animation block.</p><p>We get a lot of conveniences when using SwiftUI. For it to work for us, not against us, there are certain rules we should follow when structuring our View’s code.</p><h3>SwiftUI Concepts I’ll Be Talking About</h3><p>Three key players affect how SwiftUI manages and updates the views:</p><p><strong>1. Identity</strong></p><p>How SwiftUI recognizes views as same, or unique across multiple updates of your app. There are two types of identities to help SwiftUI differentiate views.</p><p><strong>2. Lifetime</strong></p><p>Lifetime is how SwiftUI tracks the existence of views and data over time.</p><p><strong>3. Dependencies</strong></p><p>How SwiftUI understands when your interface needs to be updated and why.</p><h3>Identity</h3><h4>Explicit identify</h4><p>For example, in UIKit, UIViews are classes, thus they have unique pointers. If two UIViews share the same pointer, then we can guarantee that they are the same view. Pointer identity is an example of <strong>explicit identity</strong>.</p><p>SwiftUI doesn’t use pointers because SwiftUI Views are structs, thus value types. Examples of explicit identity in SwiftUI: the id parameter passed to ForEach() provides a way to explicitly identify different views.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/890880ec36cdaae2c48d129ad1e837e2/href">https://medium.com/media/890880ec36cdaae2c48d129ad1e837e2/href</a></iframe><h4>Structural identify</h4><p>A view can still have an identity if it doesn’t have an explicit identity. SwiftUI generates <strong>implicit identity</strong> based on the structure of your view hierarchy, this is why you don’t have to explicitly assign an identity to every view.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bee7e8b6fafc9500c3b99cfa37687a10/href">https://medium.com/media/bee7e8b6fafc9500c3b99cfa37687a10/href</a></iframe><p>In the first example, SwiftUI sees the if statement as two different views. Each if statement is a different view, thus each view has a distinct identity. The animation will be is fade in/fade out (this is the default animation when the view is added or removed in SwiftUI).</p><blockquote>Use branch (if-else) only when you want to add or remove views.</blockquote><p>In the second example, SwiftUI recognizes the view as the same view, with a consistent identity. Thus the animation will be transitioned smoothly (the second approach is recommended).</p><blockquote>Preserving identity is recommended as it also preserves state.</blockquote><h4>Lifetime</h4><p>Identity changes signal the end of a lifetime. A view’s lifetime is tied to its identity. Thus if you want to keep the state consistent, you must make sure its identity is assigned correctly.</p><blockquote>A view’s lifetime is the duration of the identity. State lifetime is equivalent to view lifetime</blockquote><p>When the identity changes, the state is replaced. Consider the following example where we can the Marshall speaker’s volume can be adjusted after it’s instantiated:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/201ac78d4c114b5a15936a6e24ebfc96/href">https://medium.com/media/201ac78d4c114b5a15936a6e24ebfc96/href</a></iframe><p>Imagine inside our app, the user increased the volume of our Stanmore Speaker. What SwiftUI does is creates temporary storage for the new value, and compare to know if the view has changed. After the comparison, the value is destroyed. Remember how structs in Swift are value types? When a property on the struct is changed, the value of the struct changes: a new struct value is created to replace the old value. However, even if the values changed, the View hasn’t changed. <strong>View values are different from the view identity</strong>. It is still the same view.</p><p>Once a view appears on the screen (after SwiftUI calls onAppear), as your views update, new values are created for the view, but SwiftUI sees them as representations of the same view. In other words, the identity of your view hasn’t changed, thus its lifetime is still ongoing. Once the identity of the view changes, or if the view is removed (after onDisappear is called), the view’s lifetime ends.</p><p>With that in mind, let’s look at how persistent data comes into play with SwiftUI. I’ll keep using the MarshallSpeaker example from above. Consider the following case:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85ea4f6abfdd089cc2b593efd5bc63c0/href">https://medium.com/media/85ea4f6abfdd089cc2b593efd5bc63c0/href</a></iframe><p>This is one of many ways to display a Stanmore speaker based on whether reduce loudness mode is on. When ContentView first appears in the view hierarchy, MarshallSpeaker with a max volume of 70 is allocated and given an identity in the true case. When isReduceLoudnessOn changes to false, a new MarshallSpeaker is allocated with a max volume of 100.</p><p>SwiftUI recognizes the two MarshallSpeaker as different views due to their distinct identity. It allocates storage for the false case and destroys the previous MarshallSpeaker once done. As mentioned earlier, this type of structure will have a different effect on the animation that is applied to your views.</p><p>Aside from the animation, the state variable volume is destroyed with the destruction of the previous MarshallSpeaker. A new set of the state is initialized with initial values with the creation of the new MarshallSpeaker.</p><blockquote>Persistence of your state is tied to the lifetime of your views. The lifetime of your views is tied to its identity.</blockquote><p>View values are short-lived, thus you should never rely on their lifetime. What do you use then? Identities.</p><p>In summary:</p><ol><li><strong>A view’s value is short-lived. Do not rely on its lifetime</strong>.</li><li><strong>A view’s lifetime is the duration of its identity</strong>.</li><li>You control the lifetime of your view by identity.</li><li><strong>Always provide a stable identity for your data</strong>.</li></ol><p>This helps avoid a shorter view lifetime and state loss since a new state will be initialized with the creation of views with a new identity.</p><blockquote>Avoid assigning new identities to views unnecessarily. Try to keep the view’s identity stable.</blockquote><h3>Dependencies</h3><p><strong>Dependencies</strong> are inputs to the view.</p><p>Views with dependencies form a dependency graph. <strong>SwiftUI forms a dependency graph to efficiently update only those views that require a new body</strong>. When the dependencies change, only those views dependent on those dependencies will be invalidated. In other words, SwiftUI will call each view’s body, producing a new body value for each view.</p><p>Earlier I talked about:</p><blockquote>A view’s value is short-lived.</blockquote><p>Because Views are struct, thus each time a change happens on the view, the value of the view changes. The struct value is used by SwiftUI for comparison, but the view itself has a longer lifetime. <strong>The view value is not the same as the view’s life cycle</strong>.</p><p>Identity is tied to the view’s lifetime; Dependencies cause a new body to be produced for invalidated views, thus changing the value of the views, but the identity (lifetime) of the views can remain unchanged.</p><h3>Reasons to Keep Identity Consistent</h3><p><strong>1. An identifier that isn’t stable can result in a shorter view lifetime</strong></p><p>The lifetime of a view is the duration of its identity, and that means the stability of an identifier is crucial.</p><p><strong>2. Having a stable identifier helps performance</strong></p><p>Minimizes dependency update: SwiftUI no longer needs to continually allocate memory space for the view and updating the dependency graph unnecessarily.</p><p><strong>3. Avoid state loss</strong></p><p>When you give correct instructions to SwiftUI that the views before and update the view are the same view, SwiftUI no longer destroys the previous view and instantiates a new view with the state being recreated with default values.</p><h3>Tips on Keeping Identity Consistent</h3><h4>With Explicit Identity</h4><p>Start by giving your items stable identifiers.</p><ol><li><strong>Use stable identifier for identity</strong></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6293115d5cfec5b025f3817fc38027f3/href">https://medium.com/media/6293115d5cfec5b025f3817fc38027f3/href</a></iframe><p>In the above example, The id of a Book is given a new value any time the book list is reconstructed. Thus SwiftUI always recognizes them as different views. Use a persistent id. For example, use the id assigned by your database. An identifier shouldn’t change over time. A new identifier represents a new item with a new lifetime.</p><p><strong>2. Use unique identifiers</strong></p><p>Make sure the identifier belongs to one, and only one item. Otherwise, SwiftUI can’t figure out the right data to show. It helps performance too. The likely consequence of reusing identifiers (based on my experience this is usually due to human error) would be not seeing the views be rendered.</p><h4>With Structural Identity</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85ea4f6abfdd089cc2b593efd5bc63c0/href">https://medium.com/media/85ea4f6abfdd089cc2b593efd5bc63c0/href</a></iframe><p>This is the same example used before. A quick reminder: the if statement represents a branch in logic, thus the view will have a new identity when the state changes. To improve upon it, we can remove the branch to merge the two cases into a single identity:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27a32f38d6b551467e2d2ae32b3dd2ab/href">https://medium.com/media/27a32f38d6b551467e2d2ae32b3dd2ab/href</a></iframe><p>Mastering these three concepts allows you to understand how SwiftUI decides what needs to change, how, and when. The result will leave you less confused in front of tricky workarounds.</p><h3>More resources:</h3><p>This post is inspired by my favorite talk from WWDC 2021: “Demystify SwiftUI”.</p><p>If you want to learn more about the fundamentals of SwiftUI, WWDC has excellent presentations for you to follow along.</p><p>Below is a list that I think should get you started in no time:</p><ul><li>SwitUI essentials in WWDC 2019</li><li>Data Flow Through SwiftUI inWWDC2019</li><li>Building Custom Views Using SwiftUI in WWDC2019</li><li>Data essentials in SwiftUI in WWDC 2020</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=455c9ee17235" width="1" height="1" alt=""><hr><p><a href="https://medium.com/4-minute-swift/swiftui-behind-the-scene-455c9ee17235">SwiftUI Behind The Scene</a> was originally published in <a href="https://medium.com/4-minute-swift">4 Minute Swift</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started With the Combine Framework in 2021]]></title>
            <link>https://medium.com/better-programming/getting-started-with-the-combine-framework-in-2021-e8c1bfb9db1a?source=rss-91648a57c5fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8c1bfb9db1a</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Jianyuan Chen]]></dc:creator>
            <pubDate>Thu, 10 Jun 2021 14:47:40 GMT</pubDate>
            <atom:updated>2021-06-12T21:49:57.085Z</atom:updated>
            <content:encoded><![CDATA[<h4>Everything you need to know to use Combine in your production code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFHl1oYU172x7BIL4T1naQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@joshuaryanphoto?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Joshua Reddekopp</a> on <a href="https://unsplash.com/s/photos/coding?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>It’s been a while since Apple introduced the Combine framework with iOS 13 in 2019, but I only recently decided to learn it because the majority of active iOS devices are now running iOS 13. There are plenty of resources on the internet (free or paid, reads or code-along) that talk about Combine at all levels. However, I spent many nights feeling confused after going through countless articles before feeling confident enough to write my first import Combine in the production code of my current project.</p><p>If you feel the same after spending time learning about Combine, this article is for you.</p><p><em>This article only covers the basics of Combine. For example, complex usages like creating custom </em><em>Publishers and </em><em>Subscribers will be introduced in a separate article.</em></p><h3>Key Players in Combine</h3><p>Out of all the new concepts you must understand to become an expert, Combine has three key players: Publishers, Subscribers, and operators.</p><h3>Publishers</h3><p>A Publisher is a protocol with a signature of Publisher&lt;Output, Failure&gt; and is expected to deliver zero, one, or more values of the same type. It must indicate whether it can emit errors. If it does emit errors, we mark its failure to the error type. If it does not emit any errors, we use Never as failure. A Publisher completes without errors or with an error of the type specified in Failure.</p><p>A Publisher in Combine is analogous to a publisher in journalism. A journal publisher (or press) delivers content, regardless of the format. For example, it can be a traditional press that publishes weekly (e.g. <em>Time </em>magazine). It outputs multiple values and does not expect to break this pattern, meaning you can always expect <em>Time</em> magazine to come up with a new issue every week.</p><p>Another example of a publisher can be a digital publishing company that operates a news publishing service. You don’t know how many notifications you are going to receive on your phone — one or several a day. They can push Lorem Ipsums to your phone by accident. Or when you click on the notification, it crashes while opening the app instead of directing you to the correct article. This is how the publisher emits an error. The difference between this and Combine’s Publisher is that in Combine, once a Publisher emits an error, the Publisher is considered complete. In the case of your news app, you can keep getting buggy notifications if the bugs aren’t fixed.</p><p>In summary, a Publisher:</p><ul><li>Has a signature of Publisher&lt;Output, Failure&gt;.</li><li>Outputs zero, one, or multiple values of the same type over time.</li><li>Can publish an error type to signal the Publisher has failed, and the Publisher will complete.</li><li>Can complete without any errors.</li></ul><h4>Useful Publishers</h4><p>Combine comes with a million ways to initialize a Publisher. There are dedicated publishers for us to use for certain common tasks.</p><h4>Just&lt;Output&gt;</h4><p><a href="https://developer.apple.com/documentation/combine/just">Provides a single value</a> and completes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7344403900de33cd84aeab8245f52ab/href">https://medium.com/media/e7344403900de33cd84aeab8245f52ab/href</a></iframe><p>It can’t fail with an error. This is why the output value is the sole argument required to initialize a Just publisher.</p><h4>Future&lt;Output, Failure&gt;</h4><p><a href="https://developer.apple.com/documentation/combine/future">Initialized with a closure</a> that eventually resolves to a single output value or failure completion.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec388763e6e6d435e0acb9d1d649fffe/href">https://medium.com/media/ec388763e6e6d435e0acb9d1d649fffe/href</a></iframe><p>Future is like promises in Javascript. It takes a callback, and in there, you are free to return a .success or .failure when you desire (e.g. when you want to do an asynchronous task). After processing your request, the Publisher will emit the value you specify (namely, success or failure).</p><h4>@Published</h4><p><a href="https://developer.apple.com/documentation/combine/published">A property wrapper</a> that creates a Publisher for this type. The Publisher can then be accessed with the $ operator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6aea7593d668a0c0244a373a6fbcef2b/href">https://medium.com/media/6aea7593d668a0c0244a373a6fbcef2b/href</a></iframe><p>One thing to remember when using @Published: The @Published attribute is class-constrained. You can only mark it for properties of a class — not for properties of a struct. The compiler will complain if you try to do so. It also cannot be used in protocols.</p><p>Although there are other ways to achieve the same thing, @Published is merely letting Combine do the heavy lifting. Alternatives will be introduced later.</p><p><em>To learn more about property wrappers, </em><a href="https://www.swiftbysundell.com/articles/property-wrappers-in-swift/"><em>John Sundell</em></a><em> wrote an extensive introduction on this topic</em>.</p><h4>Publisher and Foundation</h4><p>Apple also introduced many helpers to Foundation so you don’t always have to write a custom Publisher every time you want to interact with Foundation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c502884fed9180d25407b99de0a980a/href">https://medium.com/media/2c502884fed9180d25407b99de0a980a/href</a></iframe><h3>Subscribers</h3><p>Deriving a Publisher is the first step in using Combine. A Publisher alone cannot achieve anything useful until it is attached by a Subscriber. Publishers and Subscribers are meant to be connected. A Subscriber is a protocol with a signature of Subscriber&lt;Input, Failure&gt;. Attaching the Subscriber to the Publisher results in a Subscription.</p><p>Imagine you are a subscriber of <em>Time</em> magazine (i.e. you are in a subscription relationship with the <em>Time</em> magazine publisher). One characteristic of this subscription is that you can expect to receive a copy of the latest issue of <em>Time</em> when it is published. You expect to be sent a copy of <em>Time </em>—<em> </em>not <em>National Geographic</em>. This is true in Combine: The output of the publisher must match the input of the subscriber. The failure type of the publisher must match that of the subscriber.</p><p>You should be familiar with the cancellation policy of most subscription services nowadays. At any point during your subscription period, you’re free to drop out or cancel the subscription. Alternatively, the subscription is automatically canceled if <em>Time</em> magazine ceases business. You won’t get any new issues from the magazine.</p><p>Combine allows you to cancel the subscription at any time.</p><p>After a Subscriber subscribes to a Publisher, you get an object that conforms to the Cancellable protocol:</p><ol><li>You can cancel the subscription manually by calling subscription.cancel().</li><li>The subscription is automatically canceled if it has been deallocated.</li></ol><p>Store the subscription since it will cancel automatically if it is deallocated.</p><p>In summary, a Subscriber:</p><ul><li>Is linked with one subscription. A Subscriber cannot subscribe to multiple Publishers.</li><li>The Subscriber’s input and failure type must match that of the publisher.</li><li>You need to store the subscription somewhere to avoid it being deallocated.</li></ul><h4>Useful Subscribers</h4><h4>.sink(receiveCompletion: receiveValue:)</h4><p>A convenient Subscriber <a href="https://developer.apple.com/documentation/combine/subscribers/sink/init(receivecompletion:receivevalue:)">provided by Combine</a> that allows you to process the value once it is emitted by the Publisher. Immediately requests a value from the Publisher, then waits for incoming values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77d0002f3f39d9b43cc79fc1e0913c06/href">https://medium.com/media/77d0002f3f39d9b43cc79fc1e0913c06/href</a></iframe><p>As long as the subscription is kept alive, it accepts values emitted by the Publisher and forwards them to sink.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bf8239eeda92ae859c3cc841b001b8b/href">https://medium.com/media/6bf8239eeda92ae859c3cc841b001b8b/href</a></iframe><h4>.assign(to: on:)</h4><p><a href="https://developer.apple.com/documentation/combine/just/assign(to:on:)">Assigns each element</a> from a publisher to a property on an object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cae6c9236fbfc8ab573e36cce3e7bf81/href">https://medium.com/media/cae6c9236fbfc8ab573e36cce3e7bf81/href</a></iframe><p><em>Note: At the time of writing, using </em><em>.assign(to: on: self) will cause retain cycle. This is reported as a bug. A </em><a href="https://forums.swift.org/t/does-assign-to-produce-memory-leaks/29546/9"><em>temporary workaround</em></a><em> is available.</em></p><h4>Subjects</h4><p>Subjects are special because they behave like both Publishers and Subscribers. Normally, a Subscriber gets its inputs from Publishers. Subjects are Publishers after they are initialized and give you the freedom to send values on demand.</p><p>Combine provides two convenient and useful subjects for us.</p><p><a href="https://developer.apple.com/documentation/combine/passthroughsubject">PassthroughSubject&lt;Output, Failure&gt;</a>:</p><p>PassthroughSubject doesn’t have an initial value or store any values at any point during the subscription. It acts as a publisher whose sole job is to relay the value to subscription operations down the line.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67ad1b9f25442e56d412e84a0538485a/href">https://medium.com/media/67ad1b9f25442e56d412e84a0538485a/href</a></iframe><p><a href="https://developer.apple.com/documentation/combine/currentvaluesubject">CurrentValueSubject&lt;Output, Failure&gt;</a>:</p><p>The initialization of a CurretValueSubject requires an initial value. You can access the value stored with subject.value any time. Changing the value will cause the subject to emit the value to the subscription attached to it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/766ce264160e9050406c2ca58184c9d9/href">https://medium.com/media/766ce264160e9050406c2ca58184c9d9/href</a></iframe><h4>PassthroughSubject vs. CurrentValueSubject</h4><p>In summary, comparing CurrentValueSubject to PassthroughSubject:</p><ul><li>CurrentValueSubject has an initial value, whereas PassthroughSubject doesn’t.</li><li>CurrentValueSubject stores a value in .value. Changing the value will automatically cause the Publisher to send a new value. PassthroughSubject doesn&#39;t store any values itself. It merely passes the upstream value downstream.</li></ul><p>CurrentValueSubject is useful for stateful, mutable properties, while PassthroughSubject is good for representing events.</p><h3>Operators</h3><p>Where Combine’s functional reactive paradigm shines over others is in its readability and decorativeness. All the power lies in the operators.</p><p>Operators are functions defined on Publisher instances:</p><ul><li>Operators are chained to add processing steps.</li><li>Each operator returns a new Publisher.</li></ul><p>Operators are best explained through examples.</p><h4>.map(_ transform: (Output) -&gt; T)</h4><p>Combine’s <a href="https://developer.apple.com/documentation/combine/publisher/map(_:)-99evh">.map(_:) operator</a> works similarly to the standard .map(:) function you would use on a Collection.</p><p>.map(_:) uses a closure to transform each element it receives from the upstream Publisher.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5d0c663a24d7a2aebb479dd4f8c17f1/href">https://medium.com/media/f5d0c663a24d7a2aebb479dd4f8c17f1/href</a></iframe><p>We started with an array of integers and created a Publisher using one of Combine’s convenient methods to turn the Foundation entities into publishers. .map comes in handy when we need to process the values additionally. In this case, upstream values are transformed from Integer to String.</p><p>Operators can be chained. Chaining multiple .map() reminds me of the <em>Single Responsibility Principle</em>, where you would do one thing per operator. It greatly improves the readability of your Combine code.</p><h4>.filter(_ isIncluded: (Output) -&gt; Bool)</h4><p><a href="https://developer.apple.com/documentation/combine/just/filter(_:)">.filter()</a> works similarly. It takes a closure and only emits values that meet the requirement specified in the closure. Other values will not be emitted downstream.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32c9f948efd34cdafde5be375550e9e7/href">https://medium.com/media/32c9f948efd34cdafde5be375550e9e7/href</a></iframe><p>Operators are meant to work together. In the example above, we first filter out odd numbers, then transform them into strings. Finally, we can use the value.</p><h4>.removeDuplicates()</h4><p><a href="https://developer.apple.com/documentation/combine/fail/removeduplicates()">Removes repeating elements</a> from upstream Publishers.</p><p>.removeDuplicates() doesn’t keep track of all values emitted but works with a two-element memory. The comparison is based on the current value and the previous value.</p><p>For example, if the values are 0, 1, 1, the emitted values will be 0 and 1. If the values are 0, 1, 0, 1, the emitted values will still be 0, 1, 0, 1 since no adjacent elements are equal.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6359acb9d5c0671d77bebebc19ed5588/href">https://medium.com/media/6359acb9d5c0671d77bebebc19ed5588/href</a></iframe><h4>.compactMap(_ transform: (Output) -&gt; T?)</h4><p><a href="https://developer.apple.com/documentation/combine/publishers/catch/compactmap(_:)/">.compactMap()</a> takes a transform closure that returns an optional, and only non-nil optional results will be returned to the downstream Publisher. Nil optionals will be removed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d41da23651122ae87f6da9ab47c6bdd/href">https://medium.com/media/5d41da23651122ae87f6da9ab47c6bdd/href</a></iframe><h4>.combineLatest&lt;P&gt;(_ other: P)</h4><p>The method is called on a Publisher <a href="https://developer.apple.com/documentation/combine/just/combinelatest(_:)">to combine multiple </a><a href="https://developer.apple.com/documentation/combine/just/combinelatest(_:)">Publishers</a>. The downstream Subscriber will receive a tuple of the most recent element from combined Publishers when any emits a value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6331382fcac53f787c3631c25f68030b/href">https://medium.com/media/6331382fcac53f787c3631c25f68030b/href</a></iframe><p>Each publisher must have produced at least one value before the combined Publisher to produce any values.</p><p>.combineLatest() supports chaining. You can combine unlimited Publishers with this statement. If you need to combine fewer than four Publishers, Combine provides convenient static methods on Publishers for your command:</p><ul><li>Publishers.CombineLatest(a: _, b: _)</li><li>Publishers.CombineLatest3(a: _, b: _, c: _)</li><li>Publishers.CombineLatest4(a: _, b: _, c: _, d: _)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a3357db9113bfb428f6f7dacde1da65/href">https://medium.com/media/4a3357db9113bfb428f6f7dacde1da65/href</a></iframe><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8c1bfb9db1a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/getting-started-with-the-combine-framework-in-2021-e8c1bfb9db1a">Getting Started With the Combine Framework in 2021</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Key-Value Observing in the age of Swift]]></title>
            <link>https://jianyuan-chen.medium.com/key-value-observing-in-the-age-of-swift-f509c54fa5e8?source=rss-91648a57c5fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/f509c54fa5e8</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[avplayer]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[key-value-observing]]></category>
            <category><![CDATA[kvo]]></category>
            <dc:creator><![CDATA[Jianyuan Chen]]></dc:creator>
            <pubDate>Tue, 25 May 2021 01:54:01 GMT</pubDate>
            <atom:updated>2021-05-25T20:05:49.477Z</atom:updated>
            <content:encoded><![CDATA[<h4>Ditch the archaic syntax and write key-value observations in the Swifty way</h4><figure><img alt="Binoculars illustration by @titopixel" src="https://cdn-images-1.medium.com/proxy/1*Y_tZ2IznQi4J5pvbzV4KNw.jpeg" /><figcaption>Binoculars illustration by @titopixel</figcaption></figure><p><strong>Key-Value Observing</strong> pattern, commonly known as the <strong>KVO</strong> pattern had existed since the inception of Cocoa. It is used to notify objects about changes to the properties of other objects.</p><p>When it comes to communicating changes between logically separated parts of your app, we have several options. One of the most widely used is the Delegation pattern, as demonstrated in the following example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fd6d1c3a1f164f1a807ee237164bc48/href">https://medium.com/media/9fd6d1c3a1f164f1a807ee237164bc48/href</a></iframe><h4>Advantages of Delegation</h4><ol><li><strong>It is self-documented</strong>. Looking at the code and you will know exactly how you should use it and what it does.</li><li><strong>It is reusable</strong>. As long as you want a one-to-one relationship.</li></ol><h4>Limitation of Delegation</h4><p>Delegation is most useful when you have access to the actual implementation of the code. In the above example, we use delegate?.doSomething() at a very specific point of operation inside Child class because we have access to the implementation of Child thus we can place the delegate call where we want.</p><p>However, there are cases that just can’t be achieved with delegation.</p><p>For example, if you are working with system-provided classes like the common AVPlayer from AVFoundation, the feature that I believe every single player uses is to observe the state of the player (either playing, paused, etc.). To do that, since we can&#39;t modify the source code of AVPlayerItem, we can only ask to be notified by <a href="https://developer.apple.com/documentation/avfoundation/media_playback_and_selection/observing_playback_state">addObserver(_:forKeyPath:options:context:)</a>. <em>Even the official Apple documentation code sample is written in old syntax</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9411d971d972c0c8fe145ed381f17a14/href">https://medium.com/media/9411d971d972c0c8fe145ed381f17a14/href</a></iframe><p>Even the syntax is in Swift, we inherited the design of KVO’s API from the old Objective-C age. It is very powerful and a must-know for every developer even if we are writing more and more Swift.</p><h4>The Old Key-Value Observing</h4><p>In the code sample above, there are two pain points each marked by a comment:</p><ol><li>The observation is set up as a separate step. If you have multiple observations to set up, each observation will take up one addObserver to set up.</li><li>The notifications are handled in one place. Imagine you set up multiple observations, and here you will have to check for each notification with if keyPath == #keyPath(Your.KeyPath). And the syntax for extracting useful information from the notification is tedious to write and hard to read.</li><li>Whatever observations you set up must be explicitly removed to avoid crashes.</li></ol><h4>The New Key-Value Observing</h4><p>In Swift, we can pump new blood to the old mechanism.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79d8280423634a287cdfe5928a917312/href">https://medium.com/media/79d8280423634a287cdfe5928a917312/href</a></iframe><p><em>The ‘\.’ syntax is the Swift syntax for extracting keyPath. John Sundell had an </em><a href="https://www.swiftbysundell.com/articles/the-power-of-key-paths-in-swift/"><em>excellent article on this</em></a><em>. Reading through the first half of the article should give you enough introduction</em>.</p><p>The same place where we add observers, this time the syntax becomes .observe(_keyPath:options:changeHandler:). The options the parameter specifies whether you want the old value, the new value, or both when changeHandler is called. Just like the old syntax.</p><p>You will be given two parameters at your disposal in the callback:</p><ol><li>The object that that is observed.</li><li>change. There will be a change.oldValue and change.newValue depending on what you specified as options.</li></ol><p>One important point to remember:</p><blockquote><em>You must store the observation because it will be released from memory and the observer will be removed from the object automatically if it is no longer referenced</em>.</blockquote><p>Thus you can see I’m keeping the result of the call of .observe() until the end of the view controller&#39;s life cycle. And you do not have to explicitly call removeObserve in deInit anymore.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f509c54fa5e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Localize Image Assets in Xcode]]></title>
            <link>https://jianyuan-chen.medium.com/localize-image-assets-in-xcode-c8d63bf43087?source=rss-91648a57c5fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8d63bf43087</guid>
            <category><![CDATA[ios-localization]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[localize-image]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Jianyuan Chen]]></dc:creator>
            <pubDate>Tue, 25 May 2021 01:53:40 GMT</pubDate>
            <atom:updated>2021-05-25T17:07:17.739Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to use Xcode’s graphical interface to manage localized image assets</h4><figure><img alt="Localizing image assets interface" src="https://cdn-images-1.medium.com/proxy/1*Wz3fe8sIIkkKW-Vf0qg34w.png" /><figcaption>Localizing image assets interface</figcaption></figure><p>Xcode’s graphical interface provides a convenient and powerful way to manage image assets and you should already be familiar with how it is used if you’ve ever included images in your app.</p><p>Turns out, it not only lets you manage image assets but also allows you to localize your image assets by providing different images for different locales. All you need to do is define for which locales the assets should be used, and provide the correct localized image for each locale.</p><p>This is done for each image asset so that you can choose to localize only those worth localizing.</p><p>The same localization effect can be achieved programmatically by adding the localized images as an entirely separate image set. For example, naming the images ending in locale names image_en and image_zh_CN, then check explicitly in code the current locale with Locale.current, extract the locale identifier, and return the image accordingly.</p><p>This approach requires an extensive setup and you have to follow a very specific pattern for naming your images. Not only that, you will end up with a long list of image assets and it is difficult to maintain. If you an image is no longer needed, you have to remember to remove its localized counterparts.</p><h4>The Correct Way</h4><p>Now I will walk you through the steps to achieve this with Xcode’s graphical interface. Let’s start with a typical image asset.</p><ol><li><strong>Start by adding an image set</strong></li></ol><figure><img alt="Assets supporting one locale" src="https://cdn-images-1.medium.com/proxy/1*dBNzSLX7MzLwhItRmbg0UQ.png" /><figcaption>Assets supporting one locale</figcaption></figure><p>There’s currently only one set of assets. The same image will be used regardless of the locale.</p><p><strong>2. Focus on the image asset and find the localization option down in the right inspector panel.</strong> This is where you specify the locales to be supported.</p><figure><img alt="Find the localization option in the inspector panel" src="https://cdn-images-1.medium.com/proxy/1*Ch3Hv4BJtG1fbH-2dNEHEw.png" /><figcaption>Find the localization option in the inspector panel</figcaption></figure><p>Click the locales you want to support. As you make selections, the UI for the image assets will change accordingly.</p><figure><img alt="Pick the locale to localize" src="https://cdn-images-1.medium.com/proxy/1*0v7jMpG-IqVSDngebrbSlw.png" /><figcaption>Pick the locale to localize</figcaption></figure><p>The empty assets pointed by red arrows are created by Xcode.</p><p><strong>3. Fill in the images with appropriate the localized version</strong></p><figure><img alt="Pick the locale to localize" src="https://cdn-images-1.medium.com/proxy/1*wa9XYcVsk_CBrdfXF3ydHQ.png" /><figcaption>Pick the locale to localize</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8d63bf43087" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Responder Chain in UIKit with examples]]></title>
            <link>https://medium.nextlevelswift.com/understanding-responder-chain-in-uikit-with-examples-bb28264defc2?source=rss-91648a57c5fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb28264defc2</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[gesture-recognition]]></category>
            <category><![CDATA[responder-chain]]></category>
            <category><![CDATA[uikit]]></category>
            <dc:creator><![CDATA[Jianyuan Chen]]></dc:creator>
            <pubDate>Fri, 14 May 2021 06:57:06 GMT</pubDate>
            <atom:updated>2021-05-14T06:57:06.826Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how an event is propagated and how to handle and un-handle it</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XIdBTQ9YCyVjg1cFoxmESQ.png" /><figcaption>Illustration of Responder Chain</figcaption></figure><p>Let’s start with a <strong>quiz. </strong>Consider the view structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*6NehGxxpYYRMHhZur0bKFA.png" /><figcaption>Pop Quiz Illustration</figcaption></figure><p>We have 4 views, a root view that is provided by the view controller (White), and it has one child view with a red background (Red), and Red has one child view with a green background (Green), then green has one child view with a blue background (Blue). A UITapGestureRecognizer that prints the corresponding color is added to the White and Red, but not Green and Blue.</p><p>What would be the result if we tap on the following view?</p><ol><li>White</li><li>Red</li><li>Green</li><li>Blue</li></ol><p>Formulate your answer and read on!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3dd04614f966d670d414f94dcde5d44c/href">https://medium.com/media/3dd04614f966d670d414f94dcde5d44c/href</a></iframe><h4>What is the Responder Chain?</h4><p>Events like UITapGestureRecognizer in iOS apps are handled using <em>responder</em> objects which are instances of the UIResponder class (for exampleUIView, UIViewController are all instances). Responders receive events and the events are either <strong>handled</strong> or <strong>forwarded</strong> to another responder object.</p><p><strong>Handling an event </strong>is equivalent to attaching an event handler like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b252301ad270f64676176768fbb1cf9/href">https://medium.com/media/1b252301ad270f64676176768fbb1cf9/href</a></iframe><p>The default behavior for <strong>forwarding an event</strong> is propagating the event up the <em>responder chain</em>. In other words, the event is forwarded by the first responder (where the gesture is triggered), to its super view, to UIViewController.view, and all the way to UIApplication.</p><blockquote>The propagation will stop as soon as it reaches the object with an event handler that matches the triggered event.</blockquote><h4>Answer to the Example</h4><p>In the quiz, we have a view hierarchy: White -&gt; Red -&gt; Green -&gt; Blue. Therefore, if we tap on White, the event is handled by White since White has registered a didTapWhite().</p><p>When we tap Red, the same thing happens. Red has registered a didTapRed(), thus the tap is handled at Red. This is also why we won’t see “White” be printed out because once the event is handled, it will stop propagating.</p><p>Now things get interesting.</p><p>When we tap Green, UIKit doesn’t find a handler at Green. What will it do? It goes up the responder chain. The next item in Green’s responder chain is its super view, Red. Then it is handled at Red.</p><p>Same thing for Blue. There’s no handler at Blue, so the event goes up to Green, and finds no handler, then the event goes up to Red. There it is handled.</p><h4>Bonus: Comparison to Javascript’s Event Bubbling</h4><p>If you are familiar with Javascript, you may find the responder chain similar to Javascript’s event bubbling process.</p><blockquote>When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*hOFrmBQSfyGLGwZUMeg2Lg.png" /><figcaption>Javascript Event Bubbling Sample Code</figcaption></figure><p>The only difference is, the event will keep propagating up the tree unless you explicitly call event.stopPropagation().</p><p>In the above example, even if you click on P, you will still be alerted three times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*52KCGu7LrEVyKQog.png" /></figure><p><a href="https://medium.nextlevelswift.com/">Next Level Swift</a></p><p><em>We are always looking for talented and passionate Swift developers! Check out our writer’s section and find out how you can share your knowledge with the Next Level Swift Community!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb28264defc2" width="1" height="1" alt=""><hr><p><a href="https://medium.nextlevelswift.com/understanding-responder-chain-in-uikit-with-examples-bb28264defc2">Understanding Responder Chain in UIKit with examples</a> was originally published in <a href="https://medium.nextlevelswift.com/">Next Level Swift</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exporting and importing localization files for translators in Xcode]]></title>
            <link>https://medium.com/4-minute-swift/exporting-and-importing-localization-files-for-translators-in-xcode-7cdaea8b991a?source=rss-91648a57c5fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cdaea8b991a</guid>
            <category><![CDATA[localization]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[string]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[export-localization]]></category>
            <dc:creator><![CDATA[Jianyuan Chen]]></dc:creator>
            <pubDate>Tue, 11 May 2021 05:40:57 GMT</pubDate>
            <atom:updated>2021-05-11T18:49:16.179Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let Xcode find localization strings and compile them into files for easier translation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*euC9YRv8xiv4Sg8eBr3GWA.jpeg" /><figcaption>Localization illustration by <a href="https://www.pexels.com/@esther-234072?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Esther</a> from <a href="https://www.pexels.com/photo/close-up-photo-of-baggage-sign-746500/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>Xcode had evolved a lot, making it easier than ever to make your app support multiple languages. This post will focus on exporting and importing localization files using Xcode and assumes you have enough knowledge about the process of localization or internalization.</p><p>If you need more information on implementing localizations, here are my article recommendations:</p><ol><li>Long and thorough: <a href="https://www.raywenderlich.com/250-internationalizing-your-ios-app-getting-started"><strong>Internationalizing Your iOS App: Getting Started</strong></a> from <strong>raywenderlich.com</strong> (25-minute read)</li><li>Short: <a href="https://medium.com/doyeona/localizations-in-swift-ff3e580e3605"><strong>Localizations in Swift</strong></a> by <strong>Doyen</strong> (4-minute read)</li></ol><h4>Disclaimer:</h4><p>The content in this article requires you to be familiar with the process of internationalization in Xcode.</p><p>Follow any of the articles and you will have learned enough about the processes of making your app support multiple languages.</p><p>However, I find them (and many of the other articles online) missing an essential topic: exporting localization string files for translators and importing the translated files back to the project.</p><h4>The Painful Experience</h4><p>For example, <em>Doyeon</em> relies on Xcode to generate the string files for both languages (English and Korean) but manually copies the strings in the English strings file to the Korean strings file. The author of the <em>Raywenderlich</em> article adopts the same procedure.</p><p>Keeping your language files in sync manually is fine for small projects when you only support 2 languages and your app contains only a few predefined labels. This can quickly get tedious once you start adding more labels and more languages.</p><h4>The Correct Way</h4><p>There is actually a lesser-known functionality built into Xcode to simplify the process for us.</p><p>All you need to do is use NSLocalizedString for all your strings you wish to support localization:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0119173d2024b7e8aa5aef1d192e9b9e/href">https://medium.com/media/0119173d2024b7e8aa5aef1d192e9b9e/href</a></iframe><ol><li>Select <strong>Product -&gt; Export Localization -&gt; Your Target</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*_z447z1JUD2nZuL9UWZCqA.png" /><figcaption>Choose export for your target</figcaption></figure><p><strong><em>If you can’t find the option, on earlier versions of Xcode, try the following:</em></strong></p><ol><li><strong>Focus on your project and select either the project or Target</strong> (This step is very important as the <em>Editor</em> tab will display different options depending on where you are in your project navigator. See picture below)</li><li><strong>Editor </strong>-&gt; <strong>Export Localization</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*npGfKP9A0v4q9_vo9thpIw.png" /></figure><p>This allows Xcode to automatically find all the strings that you marked as to be localized (both in storyboards and code). You just fill in your development language while you are developing, and no more copy strings in strings files.</p><p>2.<strong> Then you will be prompted to save the files.</strong> Choose the languages you wish to localize. All locales are selected by default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*5aIP_MLFhLPDpEqa4Ri7gg.png" /><figcaption>Choose the language to export</figcaption></figure><p>3. <strong>Locate the result of the export.</strong> Files are in the following structure:</p><p>The folder structure represents the locales that you are supporting. Do not change the name of the folder and any of the files, as Xcode relies on them for import later. The files and folder structure are identical for each locale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*j-Hpljvw8Al_6H0TiYU13A.png" /><figcaption>File structure after export</figcaption></figure><p>Normally, you would develop in one language, and that language will be your <em>development language</em> (see the picture in step 2). The development language does not need to be translated since you already filled in the value as you are developing.</p><p>Now, many third-party tools make it easier to work with .xliff files. I’m using a free one <a href="https://apps.apple.com/us/app/xlifftool/id1074282695?mt=12">XLIFFTool</a>. There are some paid options too which promise better UI and additional features. But if you are just filling in the blanks, XLIFFTool gets the job done at no cost.</p><p>4. <strong>Open the .xliff file in your xliff editor</strong>.</p><p>The exact procedure differs by tools. But for XLIFFTool mentioned above, drag the zh-Hans.xliff file onto the XLIFFTool icon and it will open the file automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*7Xm0_J4I_rtnHI-zUEJq0Q.png" /></figure><p>5. <strong>Put your translation in and save the file.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*BPDqpgKPbNPvst6rWOXe8A.png" /></figure><p><strong>6. Last but not least, find <em>Import Localizations</em> in the Xcode menu</strong>.</p><p>If you can’t find the option, see step 1 to make sure your Xcode is focused on your project name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*V6BY1hy16F5w9gUTjGLoUg.png" /></figure><p>7. <strong>Choose the entire folder and click Import.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l2SxEggcDykt7c6y8bv7oQ.png" /></figure><p>Run the app and switch the locale of your device to see the change!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cdaea8b991a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/4-minute-swift/exporting-and-importing-localization-files-for-translators-in-xcode-7cdaea8b991a">Exporting and importing localization files for translators in Xcode</a> was originally published in <a href="https://medium.com/4-minute-swift">4 Minute Swift</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with AVPlayer’s jerky progress bar in Swift]]></title>
            <link>https://medium.nextlevelswift.com/working-with-avplayers-jerky-progress-bar-in-swift-5dd0f58e7c34?source=rss-91648a57c5fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dd0f58e7c34</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[avfoundation]]></category>
            <dc:creator><![CDATA[Jianyuan Chen]]></dc:creator>
            <pubDate>Thu, 06 May 2021 07:54:05 GMT</pubDate>
            <atom:updated>2021-05-06T07:54:05.377Z</atom:updated>
            <content:encoded><![CDATA[<h4>and how to track UISlider events without setting up multiple action handlers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bW3Z8lGP2xW_43Ey0alhQA.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@donaldtong94?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Donald Tong</a> from <a href="https://www.pexels.com/photo/black-camera-recorder-66134/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><h3>The Requirement</h3><p>I started implementing an AVPlayer with standard capabilities. The user can play, pause, and drag the slider (implemented with an UISlider) to seek a point in the video.</p><p>While dragging, the player will stop updating the slider with the current progress derived from player.currentTime() / player.duration. Usually, this is done by setting up an observer with player.addPeriodicTimeObserver :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf98e2961b29e34d4ff1b6a810e5ace5/href">https://medium.com/media/bf98e2961b29e34d4ff1b6a810e5ace5/href</a></iframe><p>Instead, the slider.value will be used to calculate and reflect the progress pointed by the user’s dragging. Once the user releases the slider, we use player.seek() to continue playing the video from the time converted from slider.value:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd43c1e39e0d627e12152118d0a83472/href">https://medium.com/media/dd43c1e39e0d627e12152118d0a83472/href</a></iframe><h4>Tracking the Slider events</h4><p>On the slider, I want to track the following events:</p><ol><li>When the slider is held down</li><li>When the slider is being dragged</li><li>When the slider is released</li></ol><p>Initially, I started by adding multiple targets to handle user interactions with the slider. For example, I wanted to add a .touchUpInside to handle release, and .valueChanged with sider.isContinuous set to true to continuously trigger an update on the current time label.</p><p>Giving that a second thought, don’t the requirements sound like a statement: “Start tracking the slider when it is held down; Keep tracking the slider while it is being dragged; Stop tracking when the user releases the slider”?</p><p>Gracefully, UIControl has a <a href="https://developer.apple.com/documentation/uikit/uicontrol/1618210-istracking">.isTracking</a> property that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*t2XbXPiSe7z0rUGNzU6sOA.png" /><figcaption><a href="https://developer.apple.com/documentation/uikit/uicontrol/1618210-istracking">https://developer.apple.com/documentation/uikit/uicontrol/1618210-istracking</a></figcaption></figure><p>This property is better suited than setting up multiple actions since it returns false if the user isn’t interacting with the control and returns true if it detects the user is interacting with the control.</p><blockquote>Some answers on StackOverflow mentioned using <a href="https://developer.apple.com/documentation/uikit/uicontrol/1618231-ishighlighted">.isHighlighted</a> to simulate tracking. However, isHighlighted will only track the highlighted state. Do you know that highlighted becomes false as soon as you move your finger away from the center of the control, even if you are still holding down the slider and its value is constantly being updated?</blockquote><p>Setting up the method to track .isTracking is very convenient and readable thanks to the new syntax of adding observers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/334ef10c421d806292881457cb9325cb/href">https://medium.com/media/334ef10c421d806292881457cb9325cb/href</a></iframe><p>Just remember to save the observer to a variable since the observer will stop observing as soon as the returned observer is deallocated. Thus you want the ARC to hold on to it until you don’t need it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*fkXGaKGT7AJiuFZyYk8xbA.png" /></figure><p>After all the setup, since the two operations (period time observer notification &amp; seek operation) run separately, I used a flag isScrubbingInProgress to stop the periodic time observer from updating the progress bar while the user is dragging the slider:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/235d86be73cb7e0026811ae00cf7ea54/href">https://medium.com/media/235d86be73cb7e0026811ae00cf7ea54/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4225e4b23e21e7f5151ba5157556db8/href">https://medium.com/media/c4225e4b23e21e7f5151ba5157556db8/href</a></iframe><p>It works like a charm! Functionality-wise.</p><p>Then there comes the problem.</p><h3>The Issue</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*YvkfzLBstf5Nq89JndsNBQ.gif" /><figcaption>Slider behavior before treatment</figcaption></figure><pre>&gt; Debugger</pre><pre>manual seek started<br>isDragging == false<br>periodic time: 3.558641275 // &lt;-- 🚩!<br>periodic time: 11.874<br>Player time after seeking: 11.874</pre><p>This is what happened: The <strong>flash</strong>. Yes, in details:</p><ol><li>Once the slider started tracking the drag, the periodic time observer no longer updates the progress since we set isScrubbingInProgress = true to prevent the UI update.</li><li>As soon as the slider is released, we seek to wherever the slider’s value is.</li><li>Since we setisScrubbingInProgress = false on releasing the slider, the periodic time observer can update the progress bar UI. <em>However fast the seek operation is, it will take some time. Meanwhile, the periodic time observer will update the progress bar UI before the seek operation is finished.</em></li></ol><p>This is why you see the periodic time is 3.5, then right after the following observer notification, it becomes 11.8.</p><p>This doesn’t seem to be a bug, it’s just how the APIs are designed, and it is up to us developers to find a way around this.</p><h3>The Workaround</h3><p>Hopefully concise enough, all you need to do is add in another variable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2b194ba7fb35960ef936499f6867534/href">https://medium.com/media/f2b194ba7fb35960ef936499f6867534/href</a></iframe><p>This is the most convenient workaround I came up with. The log still prints the same, but this time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*aAXP-Wlo6z5WdmxaWFHNxA.gif" /><figcaption>Slider behavior after treatment</figcaption></figure><p>Thanks for reading!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lizxnDe-bUjAjYY_.png" /></figure><p><a href="https://medium.nextlevelswift.com/">Next Level Swift</a></p><p><em>We are always looking for talented and passionate Swift developers! Check out our writer’s section and find out how you can share your knowledge with the Next Level Swift Community!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dd0f58e7c34" width="1" height="1" alt=""><hr><p><a href="https://medium.nextlevelswift.com/working-with-avplayers-jerky-progress-bar-in-swift-5dd0f58e7c34">Working with AVPlayer’s jerky progress bar in Swift</a> was originally published in <a href="https://medium.nextlevelswift.com/">Next Level Swift</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create an animated slide-up menu programmatically with Auto Layout]]></title>
            <link>https://medium.nextlevelswift.com/create-an-animated-slide-up-menu-programmatically-with-auto-layout-d7cd095623d4?source=rss-91648a57c5fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7cd095623d4</guid>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Jianyuan Chen]]></dc:creator>
            <pubDate>Fri, 30 Apr 2021 20:16:04 GMT</pubDate>
            <atom:updated>2021-04-30T20:16:04.899Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building your own Action Sheet in Swift</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ubf5n6lQi6gh822TKsrDEA.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@skitterphoto?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Skitterphoto</a> from <a href="https://www.pexels.com/photo/disney-mickey-mouse-standing-figurine-42415/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>We should all be familiar with the action sheet that iOS uses in the system settings and Apple native apps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*ByauDQybt1Bf0NKFtLPX1g.gif" /></figure><p>The animation feels smooth and native, and the API for this action sheet is very straightforward. However, it lacks a bit of personality that makes your app stand out. Plus, if you work with a designer, often times the designer will give you a customized version of this and the action sheet hardly aligns with any custom design guides. So, how can we achieve the following effect programmatically with Auto Layout?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*P5sHnysu0L7kaaK8YgFssA.gif" /><figcaption>The finished product</figcaption></figure><h3>The Setup</h3><p>The demo app contains an UIViewController embedded in a navigation controller, a bar button item on the right of the navigation bar, and a label that is centered in the view. Clicking the bar button item will call out the options menu, and once you make a choice in the options menu, the label will be updated to reflect the selection.</p><p>Now, let’s take some time to plan how we want to approach this.</p><h3>Should we use a custom transition or a UIView animation?</h3><p>We have several options to continue. The first option that comes to my mind: we could definitely build a view controller with a custom transition to support the slide-up animation. However, most of the time, this would be overkill for a simple requirement. You can read about how to do this here:</p><p><a href="https://medium.com/next-level-swift/creating-an-animated-popover-with-transparent-background-in-swift-94989a664f77">Creating an animated popover with transparent background in Swift</a></p><p>In our case, all that is required is to show a list of buttons and animate them. In my opinion, a simple UIView.animateWithDuration on a UIView will do.</p><h3>The Implementation</h3><h4>1. Determine the APIs</h4><p>Next, I need to decide how I would use this, and perhaps more importantly how I would make this extendable in case I need to reuse it in the future. I’m using this inside my HomeViewController, other view controllers might have their settings too. They might have different requirements, but they all share a method like showOptions to call out the menu, and a list of options be displayed. Thus I will define a base OptionsManager to be extended by more specialized option menu managers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c79b602961c45c264a5d54c5d3d7be5/href">https://medium.com/media/3c79b602961c45c264a5d54c5d3d7be5/href</a></iframe><p>Once we have this protocol, any subsequent options manager would just inherit this and add features specific to them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83de1a8bae98ff6da4d89303a1bae2dc/href">https://medium.com/media/83de1a8bae98ff6da4d89303a1bae2dc/href</a></iframe><p>Since we are using a table view to display the options, the height can be saved as a variable, just remember to accommodate the bottom safe area on new full-screen iPhones. There are 2 things we will need to animate:</p><ol><li>A background view that covers the screen and half dim.</li><li>The actual options view as a table view.</li></ol><p>The action handlers are additional APIs we provide whoever is using this manager. optionsDidOpen and optionsDidDismiss give us a chance to do some additional setup and cleanup after the options menu is fully presented and fully dismissed. didSelectOption a lazy delegate pattern I used in this case. I would argue that delegate pattern is better for maintainability and team environment since it enforces implementation so you don’t forget to set the handler, but a variable function, in this case, saves me some typing. The below is the view controller demonstrating how I would use this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef1e453e0e5cb02a35ce4760bd18b72a/href">https://medium.com/media/ef1e453e0e5cb02a35ce4760bd18b72a/href</a></iframe><p>I use lazy to delay initialization and complete its setup like “delegate” methods. I declared the options manager as the root OptionsManager, and hey, it follows SOLID’s “Liskov Substitution Principle”!</p><h4>2. Implement animation with auto layout</h4><p>Now finally to build the views and the animations. I will be using a lovely and concise layout framework called “<a href="https://github.com/freshOS/Stevia">Stevia</a>”, the syntax should be easy to follow. Check it out if you like its syntax.</p><p>The idea is:</p><ol><li>To anchor the table view’s bottom to the background view’s bottom, plus the table view height.</li><li>Then change the constraint to equal the background view’s bottom, animate the change with UIView.animateWithDuration.</li><li>The animation block is delayed for 0.1 asynchronously to let Auto Layout complete its initial layout pass, then do the animation or the constraint change in the next layout pass. If you were to give a deadline of 0 seconds, the animation would look like this:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*XNas0005byX5GE8YL2LPUg.gif" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1538397aefdf08e7d734f3b5508df27b/href">https://medium.com/media/1538397aefdf08e7d734f3b5508df27b/href</a></iframe><h4>3. Wire up “delegate” methods</h4><p>Lastly, wire up the table view with the standard table view data source and delegate methods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65226df380ad5a1ae9d57b1bf33938f4/href">https://medium.com/media/65226df380ad5a1ae9d57b1bf33938f4/href</a></iframe><p>And there we have it, our very own custom action sheet!</p><p>The complete project can be found on my <a href="https://github.com/mhijack/AnimatedSlideUpMenu">Github page</a>. Thanks for reading!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bf-Xan1Qz0vwQJg1.png" /></figure><p><a href="https://medium.nextlevelswift.com/">Next Level Swift</a></p><p><em>We are always looking for talented and passionate Swift developers! Feel free to check out our writer’s section and find out how you can share your knowledge with the Next Level Swift Community!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7cd095623d4" width="1" height="1" alt=""><hr><p><a href="https://medium.nextlevelswift.com/create-an-animated-slide-up-menu-programmatically-with-auto-layout-d7cd095623d4">Create an animated slide-up menu programmatically with Auto Layout</a> was originally published in <a href="https://medium.nextlevelswift.com/">Next Level Swift</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Localize Timezone display names in Swift]]></title>
            <link>https://medium.com/4-minute-swift/localize-timezone-display-names-in-swift-4d60132cfc26?source=rss-91648a57c5fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d60132cfc26</guid>
            <category><![CDATA[conversion]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[localization]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[timezone]]></category>
            <dc:creator><![CDATA[Jianyuan Chen]]></dc:creator>
            <pubDate>Fri, 30 Apr 2021 01:06:55 GMT</pubDate>
            <atom:updated>2021-04-30T01:06:55.108Z</atom:updated>
            <content:encoded><![CDATA[<p>The time zone localization tips missing from Apple’s official documentation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lXgX3BENVjVPyIjbi93Rbg.jpeg" /></figure><p>I came across a requirement from the product team earlier today where they want to display a UTC date in the format: April 30th, 2021 (Vancouver Time), and it should be localized to the device’s active locale.</p><p>After some research, it is clear that the Foundation framework already comes equipped with the common operations you would do with time zones.</p><p>According to Apple’s documentation, you would use a TimeZone to :</p><blockquote>TimeZone defines the behavior of a time zone. Time zone values represent geopolitical regions. Consequently, these values have names for these regions. Time zone values also represent a temporal offset, either plus or minus, from Greenwich Mean Time (GMT) and an abbreviation (such as PST for Pacific Standard Time).</blockquote><h4>TimeZone construction</h4><p>A TimeZone struct can be constructed in two ways:</p><ol><li>By <strong>time zone identifier</strong>, via TimeZone(identifier: _) if your city identifier (usually in the format: &quot;America/Los_Angeles&quot;) happens to match one of the options Apple stored in the framework.</li><li>By <strong>time zone abbreviation</strong>, via TimeZone(abbreviation: _). For example “PST” stands for “Pacific Standard Time”, and its associated city, according to Apple’s data is America/Los_Angeles. This can be thought of as the most iconic city associated with the time zone abbreviation.</li></ol><p><em>The complete list of time zone identifiers can be accessed through the static variable </em><em>TimeZone.knownTimeZoneIdentifiers. (An excerpt is printed below. The complete list can be found </em><a href="https://gist.github.com/mhijack/2b63b84d96802ccc719291474ac9df72"><em>here</em></a><em>.)</em></p><pre>[<br>    &quot;Africa/Abidjan&quot;,<br>    &quot;Africa/Accra&quot;,<br>    &quot;Africa/Addis_Ababa&quot;,<br>    &quot;America/Argentina/Buenos_Aires&quot;,<br>    &quot;America/Argentina/Catamarca&quot;,<br>    &quot;Antarctica/Troll&quot;,<br>    &quot;Antarctica/Vostok&quot;,<br>    &quot;Arctic/Longyearbyen&quot;,<br>    &quot;Asia/Aden&quot;,<br>    &quot;Asia/Almaty&quot;,<br>    &quot;Asia/Amman&quot;,<br>    &quot;Atlantic/St_Helena&quot;,<br>    &quot;Atlantic/Stanley&quot;,<br>    &quot;Australia/Adelaide&quot;,<br>    &quot;Australia/Brisbane&quot;,<br>    &quot;Australia/Broken_Hill&quot;,<br>    &quot;Europe/Amsterdam&quot;,<br>    &quot;Europe/Andorra&quot;,<br>    &quot;Europe/Astrakhan&quot;,<br>    &quot;GMT&quot;,<br>    &quot;Indian/Antananarivo&quot;,<br>    &quot;Indian/Chagos&quot;,<br>    &quot;Indian/Christmas&quot;,<br>    &quot;Pacific/Apia&quot;,<br>    &quot;Pacific/Auckland&quot;,<br>    &quot;Pacific/Bougainville&quot;,</pre><pre>    ...<br>  ]</pre><p><em>The complete list of time zone abbreviation to identifier dictionary can be accessed through </em><em>TimeZone.abbreviationDictionary. (Complete list can be found </em><a href="https://gist.github.com/mhijack/21059524b808cf3b0141f7109cc22fb2"><em>here</em></a><em>)</em></p><pre>[   <br>     &quot;WAT&quot;: &quot;Africa/Lagos&quot;, <br>     &quot;EAT&quot;: &quot;Africa/Addis_Ababa&quot;,  <br>     &quot;MDT&quot;: &quot;America/Denver&quot;, </pre><pre>     ...<br>]</pre><h4>TimeZone conversion</h4><p>Once you have constructed the time zone struct, you can get its localized display name with the following method:</p><p>timezone.lolicazedName(for: NSTimeZone.NameStyle, locale: Locale?)</p><p><strong>NSTimeZone.NameStyle</strong> is an enum consist of 6 options:</p><ol><li><strong>.standard</strong>: Gives the name of the time zone which usually contains the word “standard”.</li><li><strong>.shortStandard</strong>: Gives the standard time in the format of time offset from GMT +0.</li><li><strong>.dayLightSaving</strong>: Gives the daylight saving time label for the specific time zone.</li><li>.shortDayLightSaving</li><li>.generic</li><li><strong>.shortGeneric</strong>: Gives the localized name down to the city. For example, if you use the time zone “America/Vancouver”, the converted name would be “Vancouver Time”. However some countries like China have unified time zone across the country, so even though you specify “Asia/Shanghai”, the result will be “China Mainland Time” instead of “Shanghai Time”</li></ol><p><strong>Locale</strong> determines which language the returned time zone label would be translated into. For example, &quot;zh_Hans_CN&quot; gives Simplified Chinese, &quot;en_UK&quot; gives the name in British English convention. In most cases, you would want to show the name based on the current device’s active locale, which can be accessed through Locale.current.</p><p>Below are the results of printing the localized name for each name style and locale combination:</p><pre>========</pre><pre>For timezone: &quot;Asia/Shanghai&quot; and locale: &quot;en_UK&quot;<br>.standard:                     China Standard Time<br>.shortStandard:                GMT+8<br>.dayLightSaving:               China Daylight Time<br>.shortDaylightSaving:          GMT+8<br>.generic:                      China Standard Time<br>.shortGeneric:                 China mainland Time</pre><pre>========</pre><pre>For timezone: &quot;Asia/Shanghai&quot; and locale: &quot;zh_Hans_CN&quot;<br>.standard:                     中国标准时间<br>.shortStandard:                GMT+8<br>.dayLightSaving:               中国夏令时间<br>.shortDaylightSaving:          GMT+8<br>.generic:                      中国标准时间<br>.shortGeneric:                 中国大陆时间</pre><pre>========</pre><pre>For timezone: &quot;America/Vancouver&quot; and locale: &quot;en_UK&quot;<br>.standard:                     Pacific Standard Time<br>.shortStandard:                GMT-8<br>.dayLightSaving:               Pacific Daylight Time<br>.shortDaylightSaving:          GMT-7<br>.generic:                      Pacific Time<br>.shortGeneric:                 Vancouver Time</pre><pre>========</pre><pre>For timezone: &quot;America/Vancouver&quot; and locale: &quot;zh_Hans_CN&quot;<br>.standard:                     北美太平洋标准时间<br>.shortStandard:                GMT-8<br>.dayLightSaving:               北美太平洋夏令时间<br>.shortDaylightSaving:          GMT-7<br>.generic:                      北美太平洋时间<br>.shortGeneric:                 温哥华时间</pre><p>P.S.:</p><p>This <a href="https://gist.github.com/jacobbubu/1836273">github gist</a> is a list of locale identifiers for quick reference, which could be very handy during testing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d60132cfc26" width="1" height="1" alt=""><hr><p><a href="https://medium.com/4-minute-swift/localize-timezone-display-names-in-swift-4d60132cfc26">Localize Timezone display names in Swift</a> was originally published in <a href="https://medium.com/4-minute-swift">4 Minute Swift</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A better way to display an empty indicator when the table view data source is empty]]></title>
            <link>https://medium.nextlevelswift.com/a-better-way-to-display-an-empty-indicator-when-the-table-view-data-source-is-empty-f3bc32f899ed?source=rss-91648a57c5fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3bc32f899ed</guid>
            <category><![CDATA[uitableview]]></category>
            <category><![CDATA[empty-table-view]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[empty]]></category>
            <category><![CDATA[reusable]]></category>
            <dc:creator><![CDATA[Jianyuan Chen]]></dc:creator>
            <pubDate>Thu, 22 Apr 2021 03:21:08 GMT</pubDate>
            <atom:updated>2021-05-17T06:45:16.358Z</atom:updated>
            <content:encoded><![CDATA[<h3>A better way to display an indicator when the tableview data source is empty</h3><h4>Separating the logic inside the table view’s data source will make your code reusable and easier to maintain</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fCeBlhj5y9w9ku_D07WaHQ.jpeg" /><figcaption>an empty table</figcaption></figure><h3>The Requirements</h3><p>I don’t need to have expert knowledge in user experience to realize that users don’t like to be left in ambiguity. Users require an immediate and clear visual indicator of the current state of the product they are using. In real life, when there is nothing on the table, we leave it tiny like that. But in an app, we want to show some custom content when the table view is empty to tell the user about that.</p><p>If you work in a team with designers, it is their responsibility to give you, the developer, instructions on what to display if there isn’t any data to display. However, it is up to you to decide the actual implementation of the portion of your table view that the user does not see.</p><p>UITableView usage by concept is very straightforward. You create a table view, assign it&#39;s .dataSource and .delegate property to the view controller or view that owns the table view. Then you can use numberOfRowsInSection and cellForRowAt provided by UITableViewDataSource to determine the behavior of your table view.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f70590eecc46603ea363d6b1870e124/href">https://medium.com/media/4f70590eecc46603ea363d6b1870e124/href</a></iframe><p>For example, we perform the logic in numberOfRowsInSection:</p><ol><li>If the data is empty, return one cell.</li><li>Otherwise, return the count of data.</li></ol><p>The same logic incellForRowAt:</p><ol><li>If the data is empty, return our custom empty table view cell.</li><li>Otherwise, return the normal table view cell to display data.</li></ol><h3>The Problem</h3><p>Writing logic in one place works, but it usually makes the code hard to maintain and not reusable. If we want to reuse the logic in multiple places, we will need to copy and paste the same logic. Imagine the designer rolled out a re-design of the empty table view cell; we will have to find and change the logic at all places.</p><p>And?</p><p>Doesn’t that switch and case true: and case false: look ugly? We have always to remember to keep both switch statements in sync in both methods.</p><h3>The Solution</h3><p>Different UITableViewDataSource deserve to be independent. After all, all the data source does is provide instructions on how the table view is rendered. Remember how we initialize a table view, sometimes even blindly? We assign the .dataSource attribute and use the view controller as the only data source to the table view. What if we would change the data source on the fly, based on the type of data to display?</p><p>For example, if we want to show a list of users, we provide the table view with a hypothetical user data source. If we want to show an empty table view cell, we can feed the table view a different .dataSource, then do a reload to refresh the cells. If the back end later tells us the user list is no longer empty, we could swap the data source again.</p><p>In theory, this sounds feasible. In reality, this is not difficult to implement.</p><p>We will need a specialized table view subclass to manage the data source. I will call it: EmptyTableView.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bce22182ae94c912a161a8422d28e132/href">https://medium.com/media/bce22182ae94c912a161a8422d28e132/href</a></iframe><ol><li>The dependencies for the empty table view are injected during construction.</li><li>It requires an EmptyTableViewDataSource, EmptyTableViewDelegate, a regular UITableViewDataSource, and a regularUITableViewDelegate to work properly.</li><li>Both table view delegates can be omitted if you do not intend to interact with the table view.</li></ol><p>Then we specify how empty table view data is displayed by constructing a standalone EmptyTableViewDataSource:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f056f68c76e0cc7dbae828ca41e14173/href">https://medium.com/media/f056f68c76e0cc7dbae828ca41e14173/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80f9e65f4f7b35c59f2bed6d49f28431/href">https://medium.com/media/80f9e65f4f7b35c59f2bed6d49f28431/href</a></iframe><ol><li>If you have a unified design reused over the code base, it is often a good idea to enclose them in a struct to enforce the structure of the model. EmptyTableViewCellModel is used as the data for our empty table view cell. In my case, we are displaying a default image, a default string of text, and occasionally an action button triggers the corresponding delegate method.</li><li>EmptyTableViewCellConfigurator is a step further in making the table view cell reusable. For example, if the cells have the same UI elements, such as an image, a label, and a button, but a different layout, we can create a cell configurator to handle adding layout constraints to the UI elements. The table view cell only creates and owns the subviews so that the table view cell can be reused in multiple layouts.</li></ol><p>Now the setup is complete, and we can add two extension methods to show or hide the empty cell.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9ba3409b62b8cbca435d32d1f7f1eb9/href">https://medium.com/media/d9ba3409b62b8cbca435d32d1f7f1eb9/href</a></iframe><ol><li>To showEmptyCell(), both table view delegate and data source are changed from regular delegate and data source to empty delegate (if you injected during construction) and data source.</li><li>To hideEmptyCell()Reset the table view’s delegate and data source to regular.</li></ol><p>What’s left to do is to build your empty table view cell UI:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16346b53469997df7e60d04c7bd5ca2b/href">https://medium.com/media/16346b53469997df7e60d04c7bd5ca2b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kPFg8YXRZcR1esjU.png" /></figure><p><a href="https://medium.nextlevelswift.com/">Next Level Swift</a></p><p><em>We are always looking for talented and passionate Swift developers! Check out our writer’s section and find out how you can share your knowledge with the Next Level Swift Community!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3bc32f899ed" width="1" height="1" alt=""><hr><p><a href="https://medium.nextlevelswift.com/a-better-way-to-display-an-empty-indicator-when-the-table-view-data-source-is-empty-f3bc32f899ed">A better way to display an empty indicator when the table view data source is empty</a> was originally published in <a href="https://medium.nextlevelswift.com/">Next Level Swift</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>