<?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 Manuel Djirlic on Medium]]></title>
        <description><![CDATA[Stories by Manuel Djirlic on Medium]]></description>
        <link>https://medium.com/@manuel-schulze?source=rss-3c34554675f7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yWiPEljjoBMiXwpHMMTrrQ.jpeg</url>
            <title>Stories by Manuel Djirlic on Medium</title>
            <link>https://medium.com/@manuel-schulze?source=rss-3c34554675f7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 16:12:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manuel-schulze/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[5 Reasons Why Most Advanced Developer Courses Are Not Worth It]]></title>
            <link>https://medium.com/better-programming/5-reasons-why-most-advanced-developer-courses-are-not-worth-it-fe427e7cc1da?source=rss-3c34554675f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe427e7cc1da</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Manuel Djirlic]]></dc:creator>
            <pubDate>Tue, 01 Feb 2022 16:31:06 GMT</pubDate>
            <atom:updated>2022-02-01T16:31:06.412Z</atom:updated>
            <content:encoded><![CDATA[<h4>And 5 things you can do instead to grow as an iOS developer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ng9NG04DuypL6zDu" /><figcaption>Photo by <a href="https://unsplash.com/@samich_18?utm_source=medium&amp;utm_medium=referral">Samantha Borges</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There are many great entry-level iOS developer courses on Udemy, Skillshare, and the like. They are usually priced very low which makes them a great deal for aspiring coders. If you took any of these courses and applied the knowledge, you should already feel ready to write a first simple iOS application with Swift.</p><p>In your quest to land your first junior iOS developer job or even after that, you may come to a point where you think: <em>‘How do I progress from now? How do I become a better developer now?’</em></p><p>Suddenly, an email of one of those course platforms appears and offers you a great deal for an intermediate or advanced iOS developer course (maybe even taught by the same instructor).</p><p>It seems to be the next logical step and so you buy the course and after taking it, you may even take another…and another. Welcome to the course loop. And they don’t even provide that much value anymore even though they explain intermediate concepts (they do, right?). So what has changed?</p><p>Today, I will try to explain why these courses are usually not worth it and what in my opinion works much better to grow as a developer.</p><h4>1. They teach you stuff you don’t need to know</h4><p>While checking a few of the intermediate and advanced courses on iOS for this post, I’ve seen two topics appear in many of them.</p><p>First, ARKit, which is Apple’s framework to support augmented reality in your iOS applications. Augmented reality is about placing virtual objects through the camera of your device in the real world which makes them appear like they are in your living room.</p><p>Second, CoreML, which is Apple’s framework to support machine learning with your app. This helps you and your app make predictions based on input (e.g. from the camera or photos).</p><p>Don’t get me wrong, both of these things were hot topics in the past few years. These technologies are also definitely harder to grasp which makes them indeed advanced concepts.</p><p>However, all of these courses teach you only the basics which give you nothing more than a broad overview.</p><p>Additionally, these technologies are not used by 97% of the apps out there. Okay, I made that number up but I think it will be pretty accurate. That means it’s not interesting for most companies that offer (junior) developer jobs.</p><p>I’ve been working as a contractor for more than 4 years on more than 10 projects overall. I’ve never used ARKit or CoreML in any of those apps. Not for big tech companies, not for car manufacturers, not for small start-ups.</p><p>Do yourself a favor and learn these technologies when you need them and focus now on the basics every single app needs.</p><h4>2. They will not help you strive as a developer</h4><p>Speaking of those questionable skills they teach and that they barely scratch the surface of most of these topics, they will not help you grow as a developer.</p><p>There is not always a course that can help you with your current problem. There are many courses, but in real life, you will face problems that are very, very specific.</p><p>Your problems will often not look like this:</p><blockquote>How can I write this with SwiftUI?</blockquote><p>But instead:</p><blockquote>I have this one SwiftUI view with a dynamic height. It is already used at two places in our code. I don’t want to re-write it in UIKit to avoid duplicated code but I have to embed it in a UIKit scrollview which would take days to translate to SwiftUI. I need to support iOS 13–15 which makes it even harder. How can I make this work?</blockquote><p>The reality is always harder than the carefully crafted examples by teachers in these courses.</p><p>These courses give you the false sense of security that it is totally enough to take them and you will strive as a developer. Sure, they help you get started. But they won’t make you a true developer that can solve all kinds of issues.</p><h4>3. They make you feel like you do something when you don’t</h4><p>I’m currently reading the great book ‘Atomic Habits’ by James Clear. And he has a really good separation between taking action and being in motion.</p><blockquote>“I refer to this as the difference between being in motion and taking action. The two ideas sound similar, but they’re not the same. When you’re in motion, you’re planning and strategizing and learning. Those are all good things, but they don’t produce a result.” — James Clear</blockquote><p>This is especially what courses do. They make you feel like you accomplish something. That you move in the right direction. But actually, you are just learning and not practicing or executing.</p><p>In order to become a developer executing is the ultimate goal. You want to apply your knowledge in real-world projects. Courses easily make you feel like you did something but it is just the easy way that is not leading to a successful career.</p><p>Don’t take the easy path but instead take the right way which means:</p><blockquote>learning -&gt; practicing -&gt; executing.</blockquote><h4>4. They give you a wrong picture of what it means to be a developer</h4><p>As mentioned above, online courses often make it appear like a broad overview and barely scratching the surface is totally fine and enough if you want to be a great iOS developer.</p><p>But over the course of your career, you need to dive deep into a handful of topics and become an expert at those. As I was starting out, I thought it was very important for me to know every single topic in the iOS, Objective-C, and Swift environment.</p><p>I wanted to be the Mr. Know-it-all. In reality, this is not possible. iOS development is such a huge topic after more than 10 years of existence that you can’t know everything.</p><p>Maybe you think knowing a little of everything makes you more attractive for a lot of jobs. But actually, they make you less attractive for any job. You know a little of everything which means you are never the best fit for anything.</p><p>Let’s say you are one of two developers applying for a job. They look for an iOS developer and also someone who knows how to structure code in a good way and has practical experience in automatically testing code.</p><p>You know the basics of these topics, as well as the basics of ARKit, CoreML, MapKit, etc.</p><p>The other developer doesn’t know a dime about them. But he focused his learnings on good code quality and architectures as well as test-driven development (TDD). He has a few projects to showcase that.</p><p>Obviously, he will be the better fit for that job and your broad overview of everything will not be taken into account during the decision phase.</p><h4>5. They are often even taught by instructors who never created production-ready Swift apps</h4><p>The last point is obvious when you are a seasoned developer. But maybe not that clear when you start out.</p><p>Ever wondered, how some teachers have over 1,000,000 sold courses? They have courses on all of these topics: Python, HTML &amp; CSS, JavaScript, PHP, Swift, Kotlin, Java, C#, Unity Game development, machine learning, etc. More irritating is that they are not even 30 years old. How do they do it?</p><p>Exactly, they just learn that stuff in order to create a course for it.</p><p>It’s lucrative, even if one course just makes them $5, they will have made more than $5,000,000.</p><p>These course creators are not great Swift developers that are proficient in all of the topics they teach. Instead, they are teachers who know the basics of how to code.</p><p>They know the bare minimum in order to teach it to an audience of inexperienced developers.</p><p>But they can’t help you become a great developer. Sure, they can teach you those basics. But if they never worked on large-scale production-ready Swift apps, they will probably also not be able to teach you how to do just that.</p><p><em>Note: I’m not calling out every course instructor that has more than 1,000,000 courses sold. Some of them are really only specialized on one or two topics and are incredibly proficient in it. It’s just sometimes hard to tell the difference.</em></p><p>Okay, now I covered a lot of things why in my opinion most of those courses are a waste of time, energy, and money. But what can you do instead? What makes you a great developer?</p><h4>1. Take action and build stuff</h4><p>Remember what I said about being in motion and taking action?</p><p>Yes, take action. After your first online course, you should start building stuff on your own. Nothing can make it easier for you to land a job as an iOS developer than having work you could showcase.</p><p>Build a GitHub repository where you build a complete app that you can share with potential employers. I prefer one large and very good app over 10 small and half-baked apps.</p><p>It’s easy to understand. The app that is not finished and polished doesn’t show that you can do that in a job as well. You will probably not be paid for making 10 lousy apps but to work for months or years on one single app.</p><p>Go the extra mile here and make everything great. You should have at least a solid user interface that conforms to <a href="https://developer.apple.com/design/human-interface-guidelines/">Apple’s Human Interface Guidelines</a>. Make reasonable commits and have a README that explains what the app is about, how to run the application, etc.</p><p>You can create another repository, where you do weekly challenges for yourself where you take a screenshot of one cool UI element of one of your favorite apps (like Instagram, Facebook, Evernote, etc.) and try to build it yourself with SwiftUI. This will improve your skills on a UI level and also show others that you can solve design challenges.</p><p>Besides coding on these projects, you should challenge yourself over and over again. Do deliberate practice where you dive into a topic very deep and try to understand it as well as possible. You should be able to explain it easily in a job interview. Then you can move on to another topic that you currently do not really understand. Good starting points are differences between loops, if-vs guard-statements, closures, or enums.</p><h4>2. Write down your learnings and share them with the community</h4><p>Right at the beginning, this can feel a bit awkward, to say the least. You don’t know a lot about iOS development, so how can you teach others?</p><p>Well, there are three reasons why you still should.</p><ol><li>It’s good for you.</li><li>It will help others.</li><li>It is very helpful if you want to become a (lead) senior developer at some point.</li></ol><p>The first point is clear. There is actually a name for it. It’s called the <em>Feynman technique</em> named after Richard Feynman. He used to say that you learn stuff better (and also find your knowledge gaps) by teaching the stuff you learned to others. You can also revisit your writings later which makes a great reference for you.</p><p><a href="https://medium.com/taking-note/learning-from-the-feynman-technique-5373014ad230">Learning From the Feynman Technique</a></p><p>The second seems the most irritating. How can a newbie teach others? Well, you actually just need to know a little bit more than your audience in order to help them. Additionally, you just mastered something with no previous knowledge. No one can explain it in a more straightforward way, through the lens of a beginner, than you.</p><p>Lastly, it’s maybe something for the future. But senior developers, especially lead developers, need to be able to teach things to juniors and mid-level developers. Your own blog or YouTube channel helps a lot in showing potential employers that you are that kind of person. It’s overall a great skill to have as a senior.</p><p>Learn more about becoming a better writer of Swift articles in this <a href="https://www.avanderlee.com/optimization/writing-swift-articles/">great post by Antoine van der Lee</a>.</p><h4>3. Work on your soft skills</h4><p>As developers, we often tend to think that we are these nerdy experts that do not require slick marketing skills or any soft skills at all. Isn’t it enough that our code is concise and readable? That our apps work great and we are good at debugging issues?</p><p>Sadly, no.</p><blockquote>Soft skills are an important part of being a developer. They are just as important as in any other field. Sure, you should become an expert in iOS development. But in large projects with millions of users, the bureaucracy becomes more and more a thing.</blockquote><p>The whole process of development is more planned and many steps need to be followed. There are documents that need to be filled out and many meetings you need to attend.</p><p>The biggest career change for me personally in the last 4 years happened when I started taking more responsibility. I became a leader. I often get compliments on my technical skills. However, I receive way more admiration for how I act in a project. How I treat other developers. How I own the project and take responsibility. How I handle difficult situations.</p><p>And leadership and responsibility are just one part of the equation. You also need to work on your communication. Written communication as well as your speaking skills.</p><p>We tend to speak a certain language as developers. For us, a few things are obvious and don’t need explanation. A project manager with no coding experience maybe sees that completely different.</p><p>For example, in the last year, I especially had struggles discussing logically difficult tasks. We had three calls and I still had the feeling that we are not on the same page. If I would have started implementing that stuff how I thought would be the right way, I’d have to do it twice.</p><p>That’s why I started using diagrams for these sorts of problems. They give everyone a clear sense of what is going on. They show if-this-than-that in a way everyone can understand. Business and technical people can speak the same language. And a picture often says more than a thousand words.</p><p>You see communication is not just about, how you present something. But also about how you resolve misunderstandings with the help of tools.</p><p>It’s definitely one of the most important skills for your career, so you can’t start early enough on that one.</p><h4>4. Improve the basics</h4><p>As mentioned above, it doesn&#39;t make sense to learn ARKit and CoreML when you can barely write a full application in Swift. It’s just not what you need to know right now. Most applications don’t use these technologies anyway.</p><p>But what should you learn instead? What are the most important skills you should master?</p><p>Well, the following list is obviously not exhaustive and maybe misses a few things. But in my opinion, these are some of the most important topics for you as a beginner:</p><ul><li>Networking (make requests to an API).</li><li>Parsing (decode the JSON response of that request with the help of the Codable protocol).</li><li>When to use structs and when to use classes?</li><li>How to use enums in a proper way (they are incredibly powerful in Swift).</li><li>How to write concise and readable code that others can easily grasp.</li><li>Deployment (how to get an app into the store and publish it).</li><li>Testing (how can I write unit tests that will verify my code does indeed what it should).</li><li>How to handle errors in a good way so your users won’t get crashes and reasonable error messages.</li><li>How to make your UI look good on all supported devices.</li></ul><p>I want to point out two things here. All of these things are needed in almost all applications that you are going to write. So they are much better if you want to become a good developer than learning something (like ARKit) that you need for 1 out of 50 projects.</p><p>Another thing is about testing your code. This is definitely a harder topic as a beginner. However, try to write at least some tests. <em>One test is better than zero tests</em>.</p><p>You will get used to it and testing helps with three things:</p><ol><li>Testing helps you verify a lot of scenarios in an automated way. You know that it behaves how it should during implementation.</li><li>It also helps you verify that everything still works as it should when you changed something later. This gives you some calm before releasing a new version.</li><li>If you are able to write tests for your code, it is written in a way that is testable which means it is modular and not too tightly coupled. That often means that your code is written in a good way.</li></ol><h4>5. Learn specific topics you’re going to need in production-ready apps</h4><p>All of these topics from the last section are great to make you a solid developer who can tackle most stuff that will be required by entry-level jobs. However, this is only the minimum. But as you progress and take more responsibility, the more likely you will face other issues.</p><p>These are a few topics you can work on next or even in parallel when you master the basics (no worries, you don’t need to know what they are about just yet):</p><ul><li>Continuous integration and continuous deployment (CI/CD) and automating the deployment and release process as well as adding quality checks that run automatically.</li><li>Structuring your code, architectures, and design patterns.</li><li>Get proficient with Git.</li><li>Linting your code with tools like <a href="https://github.com/realm/SwiftLint">SwiftLint</a>.</li><li>Generating your assets for type-safe usage with <a href="https://github.com/mac-cain13/R.swift">R.Swift</a> or <a href="https://github.com/SwiftGen/SwiftGen">SwiftGen</a>.</li><li>Avoiding memory leaks.</li><li>Debugging your code.</li><li>Topics that will make you an expert in a certain niche of iOS development (like TDD, machine learning, augmented reality, data visualization, open-source software, game development, etc.)</li></ul><p>Look I know, I have been bashing on ARKit and CoreML quite a bit in this post. But there are use-cases for them. Maybe you are really hooked on machine learning and want to become an expert. That is totally fine. But still, I think then you are better off learning this in a self-driven way with the documentation than looking at a course priced at $10 that covers the topic for less than 30 minutes.</p><p>So for the last point on that list don’t try to add as many topics as possible (again be a specialist, not a generalist) but instead dive deep into not more than 3 topics.</p><h4>Conclusion</h4><p>Throughout this post, I’ve been telling you that advanced iOS developer courses are usually not worth it. I strongly want to emphasize the word usually. Not all of these courses are bad. Some of them are great. I even bought one of them last year and still take courses even with more than 8 years of iOS development experience.</p><p>The only thing is, I bought that course for one specific topic. It covered very deeply how to become a senior developer. It was priced at almost $2,000.</p><p>Well, quality has its price.</p><p>So before you buy such a course, make sure that you build stuff before and that there is at least one specific topic you want to learn that is covered in a large amount of time.</p><p>Also, ask yourself if the instructor is a teacher that knows how to code or an iOS developer that teaches something. This can make all the difference.</p><p>Wish you all the best! Let me know in the comments if you have any courses that you think were a great addition to your skillset that drop out of my critics above.</p><p>Thanks for your time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe427e7cc1da" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/5-reasons-why-most-advanced-developer-courses-are-not-worth-it-fe427e7cc1da">5 Reasons Why Most Advanced Developer Courses Are Not Worth It</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[Labeled Statements in Swift: How To Give Loops a Name]]></title>
            <link>https://medium.com/better-programming/labeled-statements-in-swift-how-to-give-loops-a-name-44e6fd374d9b?source=rss-3c34554675f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/44e6fd374d9b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Manuel Djirlic]]></dc:creator>
            <pubDate>Mon, 15 Mar 2021 17:40:52 GMT</pubDate>
            <atom:updated>2021-03-15T17:41:37.923Z</atom:updated>
            <content:encoded><![CDATA[<h4>Know the importance of naming your loops</h4><figure><img alt="Building with banner that reads “YOUR NAME HERE”" src="https://cdn-images-1.medium.com/max/1024/0*SFJfpe2DEeGXy2un" /><figcaption>Photo by <a href="https://unsplash.com/@austinkirk?utm_source=medium&amp;utm_medium=referral">Austin Kirk</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><p>In my opinion, Swift is a beginner-friendly programming language.</p><p>Just think about a few things we have/don’t have in Swift:</p><ul><li>We don’t have to handle pointers that point to memory addresses.</li><li>There is automatic reference counting (ARC), which takes care of counting the references to objects and releases them automatically when there are no references left.</li><li>Optionals force us to handle optional values with greater care and think about the cases when an optional value is not set.</li><li>Etc.</li></ul><p>Nonetheless, Swift also has its hidden treasures. Recently, I stumbled upon one of them while reading <a href="https://docs.swift.org/swift-book/"><em>The Swift Programming Language</em></a>: labeled statements.</p><p>In essence, they allow you to name your statements, which can become handy when working with loops or switch statements.</p><p>In this article, I will show you how to name your statements and why you should even name them.</p><p>But let’s start with the problem that labeled statements solve.</p><h3>What We Would Have To Do Without Labeled Statements</h3><p>Imagine that you’re working on a company employee lookup. You have some form of database and you get all the employees separated by their departments.</p><p>Now you need to find a single member by name. For simplicity, we’ll ignore the case where two members share the same name.</p><p>So you have a string with the name of the employee. You immediately come up with a solution that iterates over the departments with a for loop, and inside of that loop is another for loop that iterates over the members of that department.</p><p>The solution could look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4122c4e57493c60ce2c7512a3caccc47/href">https://medium.com/media/4122c4e57493c60ce2c7512a3caccc47/href</a></iframe><p>You can create a blank playground and test it out. Here is what actually gets printed to the console:</p><pre>We weren&#39;t able to find the person E. Neville in Human Resources</pre><pre>The employee was found in Development!</pre><pre>We weren&#39;t able to find the person E. Neville in Development</pre><pre>We weren&#39;t able to find the person E. Neville in Sales</pre><p>The first log was fired because we can’t find E. Neville’s in the HR department. The second statement signals that we found our employee in the development department.</p><p>Yet, we still trigger the last print statement for that department. The same is true for the last department. Even when we have already found the member we were looking for, we still don’t stop the loops from running.</p><p>We need some form of cancellation.</p><p>Now you could come up with a solution like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81812d99f48c8fc649834d666e34f52b/href">https://medium.com/media/81812d99f48c8fc649834d666e34f52b/href</a></iframe><p>We use the boolean variable employeeFound to identify if we have a match. We can use break to break out of the inner loop. With the help of our variable that becomes true when we find our member, we break the outer loop as well.</p><p>That can help us solve the problem, but it is far from elegant. We need two break statements, an if statement, and a variable that we need to correctly update.</p><p>We can do better.</p><h3>How Labeled Statements Help Us Write Concise Code</h3><p>Let’s now look at the same example, but this time, we’ll use labeled statements:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8233647104c5bcbfd015af5e8b75ef75/href">https://medium.com/media/8233647104c5bcbfd015af5e8b75ef75/href</a></iframe><p>Can you see what I did there?</p><p>I gave the outer loop a label (departmentLoop). This label doesn’t require a var or let keyword. It can just be a name followed by a colon. From that point on, we can use it to break out of this loop.</p><p>We use it inside the employee loop to tell Swift that we don’t want to break out of the inner loop, which would be the default behavior. Instead, this break command is intended to break out of the outer loop.</p><p>That removes the need for an additional if statement at the end of each iteration of the outer (department) loop. We also don’t need to keep track of another variable and find the right position to change it.</p><p>Instead, we can very clearly communicate what we want to break out from.</p><h3>Other Use Cases for Labeled Statements</h3><p>The example above describes why we would want and need labeled statements. It allows us to write less code that is more readable.</p><p>Nevertheless, there are two more use cases that I know of:</p><ol><li>Using the continue command inside of loops.</li><li>Using break commands in combination with the switch statement.</li></ol><p>Let’s go over them briefly.</p><p>The continue command is also used for loops. In contrast to the break command, it does not break out of a loop and stop its execution completely. It just starts another iteration without executing any code that follows.</p><p>Imagine that we have a person who works in multiple departments. Again, we’ll ignore the case where we have the same name in the same department more than once.</p><p>The code could look like this (\\ ... marks places where you should keep the code the same as before):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/987801e5dd90446dcf70f9ca14a72f08/href">https://medium.com/media/987801e5dd90446dcf70f9ca14a72f08/href</a></iframe><p>Now our console output looks like this:</p><pre>We weren&#39;t able to find the person E. Neville in Human Resources</pre><pre>The employee was found in Development!</pre><pre>The employee was found in Sales!</pre><p>You could achieve the same by simply using a break statement without the labeled statement. However, if you have even more loops, this could become handy.</p><p>Lastly, for switch statements, you could also use the labeled statements to break out of the following situations:</p><ul><li>You want to break out of an outer switch statement that contains a loop.</li><li>You want to break out of an outer loop that contains a switch statement.</li><li>You want to break out of an outer switch statement that contains another switch statement.</li></ul><p>Let’s look at the code of a switch example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/568a1d7e26911e498909e811c3028236/href">https://medium.com/media/568a1d7e26911e498909e811c3028236/href</a></iframe><p>We want to find our dog named Lucky. We have a switch inside another switch inside a loop.</p><p>When we find an animal that is of species dog and is named Lucky, we want to break not only from the inner switch and the outer switch but completely out of the loop.</p><p>That’s a one-liner when we use a labeled statement. The log looks like this:</p><pre>It was a different animal of species: cat</pre><pre>It was a dog but a different one</pre><pre>We found our dog Lucky!</pre><p>The result is as expected. We find Lucky in the third loop iteration and have no more iterations thereafter.</p><h3>Conclusion</h3><p>As you can already tell, labeled statements are a tool for very specific situations. You probably won’t need them on a daily or even weekly basis.</p><p>However, as developers, it is our job to have a great variety of tools in our toolbelt and select the best one for the problem at hand.</p><p>Labeled statements allow us to write concise code when we want to break out of outer loops or switch statements. They are easy to use and should be part of your toolbelt as well.</p><p>This also shows us that Swift has some hidden treasures that we rarely see and maybe don’t even know about. So never stop learning what this great language has to offer.</p><p>Thanks for your time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44e6fd374d9b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/labeled-statements-in-swift-how-to-give-loops-a-name-44e6fd374d9b">Labeled Statements in Swift: How To Give Loops a Name</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[An Overview of Built-In SwiftUI Views]]></title>
            <link>https://medium.com/better-programming/an-overview-of-built-in-swiftui-views-374ea7549bf9?source=rss-3c34554675f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/374ea7549bf9</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Manuel Djirlic]]></dc:creator>
            <pubDate>Wed, 24 Feb 2021 16:56:12 GMT</pubDate>
            <atom:updated>2021-02-24T16:56:12.891Z</atom:updated>
            <content:encoded><![CDATA[<h4>Build SwiftUI apps faster by choosing the right views</h4><figure><img alt="Phone" src="https://cdn-images-1.medium.com/max/1024/0*iRWY4wHMda36mDG4" /><figcaption>Photo by <a href="https://unsplash.com/@charlesdeluvio?utm_source=medium&amp;utm_medium=referral">Charles Deluvio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><p>SwiftUI is fun.</p><p>Personally, I really enjoy building complex and beautiful views with Apple’s new declarative UI framework.</p><p>But before you start building your own custom views, it’s a good idea to get used to the things that SwiftUI already provides you with. Knowledge of these tools and views will speed up your development and help you tremendously when it comes to creating complex user interfaces.</p><p>This article will cover the built-in SwiftUI views that Apple has already shipped. The list of views I’m going to present is sadly not exhaustive, but I will give you a clear overview of the most important SwiftUI views.</p><h3>Set Up the Project</h3><p>If you want to code along, open Xcode. On the “Welcome to Xcode” screen, select “Create a new Xcode project.”</p><figure><img alt="The ‘Welcome to Xcode’ screen of Xcode that is displayed to users on startup." src="https://cdn-images-1.medium.com/max/1024/1*Vyp0vtwBwEkchBS3OyKwIg.png" /><figcaption>Screenshot created by the author</figcaption></figure><p>On the following screen, choose the blank “App” template under the “iOS” tab:</p><figure><img alt="Selecting the app template in Xcode under the iOS section." src="https://cdn-images-1.medium.com/max/1024/1*xMhJu32WSrnb9B4pK8OhOg.png" /><figcaption>Screenshot created by the author</figcaption></figure><p>Lastly, give the project a reasonable name. I’m going with SwiftUIBuiltInViews. Make sure that you select “SwiftUI” as the “Interface” type and “SwiftUI App” for the “Life Cycle” option:</p><figure><img alt="The configuration of the Xcode project. ‘SwiftUIBuiltInViews’ is used as the name. ‘SwiftUI’ is selected as the ‘Interface’ type and ‘SwiftUI App’ for the ‘Life Cycle’ option." src="https://cdn-images-1.medium.com/max/1024/1*qsq1BYD3F_ALy6wsKt1qqA.png" /><figcaption>Screenshot created by the author</figcaption></figure><p>Click on “Next” and then pick an appropriate file destination. Hit the “Create” button and you are ready to go.</p><p>Open the ContentView.swift file that we are going to use throughout this tutorial. You should see the code on the left and the preview canvas on the right. If you don’t see the canvas, use the following shortcut to open it:</p><pre>Option + Command + return (⌥ + ⌘ + ↩)</pre><p>With the canvas displayed, start the preview with this important shortcut:</p><pre>Option + Command + P (⌥ + ⌘ + P)</pre><p><a href="https://medium.com/better-programming/xcode-8-swiftui-keyboard-shortcuts-that-will-make-you-even-faster-bc3967b75224">Xcode: 8 SwiftUI Keyboard Shortcuts That Will Make You Even Faster</a></p><p>The final result should look similar to the picture below:</p><figure><img alt="The SwiftUI preview started in Xcode and shown in the canvas on the right of the screen." src="https://cdn-images-1.medium.com/max/1024/1*11DZcxl2i85HOA6GORg0rA.png" /><figcaption>Screenshot created by the author</figcaption></figure><p>Now let’s dive into our first built-in SwiftUI view.</p><h3>The Color View in SwiftUI</h3><p>The first view we are going to look at is maybe already a little surprising. SwiftUI consists mainly of views and modifiers.</p><p>Color is a view that simply displays a rectangle in the color that you’ve provided. It can also be applied to other views as a foreground or background color through modifiers.</p><p>To get started, simply remove the Text view and the padding that Xcode created for us and replace it with the following Color view:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbcb22d2acc101a1e53c81db73a03253/href">https://medium.com/media/cbcb22d2acc101a1e53c81db73a03253/href</a></iframe><p>Creating your first SwiftUI view is as simple as that. The result should look like the following:</p><figure><img alt="Preview of the SwiftUI Color view on the right with a red color on an iPhone screen." src="https://cdn-images-1.medium.com/max/1024/1*v0Jhkq9SMqWLcLcr0JQ0pg.png" /><figcaption>Screenshot created by the author</figcaption></figure><p>As you can see, the Color view takes up all the available space by default (except the status bar in our example). You can create a colored view of several basic colors by simply accessing the Color’s lowercased static properties. The following colors are available through this (as of Swift 5.2):</p><ul><li>Clear</li><li>Black</li><li>White</li><li>Gray</li><li>Red</li><li>Green</li><li>Blue</li><li>Orange</li><li>Yellow</li><li>Pink</li><li>Purple</li><li>Primary</li><li>Secondary</li></ul><p>If you’re wondering what primary and secondary are, Paul Hudson from Hacking With Swift provided a <a href="https://www.hackingwithswift.com/books/ios-swiftui/colors-and-frames">great answer to this</a>:</p><blockquote>“For example, Color.primary is the default color of text in SwiftUI, and will be either black or white depending on whether the user’s device is running in light mode or dark mode. There’s also Color.secondary, which is also black or white depending on the device, but now has slight transparency so that a little of the color behind it shines through.”</blockquote><p>There are many initializers for the Color view, but I want to show you the one that I use the most. It takes in a color name (e.g. a color that you’ve created in your assets).</p><p>For this, go into the Assets.xcassets file and create a new “Color Set” via the plus button on the bottom.</p><figure><img alt="Xcode plus icon to add a new color asset." src="https://cdn-images-1.medium.com/max/1024/1*KrSb8Y46pht7xBhasItQyw.png" /><figcaption>Screenshot created by the author</figcaption></figure><p>Name this color “MyColor” and change the appearance to “None” in the “Attribute Inspector” (Option + Command + 4 (⌥ + ⌘ + 4)).</p><figure><img alt="Xcode option to change the appearance of a color asset in the attribute inspector." src="https://cdn-images-1.medium.com/max/1024/1*Jm-S8-nXK0qFPS30q9qf5A.png" /><figcaption>Screenshot created by the author</figcaption></figure><p>Finally, click on the color itself and replace it. I used an eight-bit hexadecimal color with the value #FFBBAA.</p><figure><img alt="The configured color assert in Xcode that has the hexadecimal value of #FFBBAA." src="https://cdn-images-1.medium.com/max/1024/1*_QGh83k51w7DUhoA14Y4gQ.png" /><figcaption>Screenshot created by the author</figcaption></figure><p>Go back into the ContentView.swift file and change the body property to the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df44592aac40f1e36ea67805a51e3f95/href">https://medium.com/media/df44592aac40f1e36ea67805a51e3f95/href</a></iframe><p>Resume your preview if it has stopped working, and the result should look like this:</p><figure><img alt="The SwiftUI Color view displayed in the preview with a value of #FFBBAA on an iPhone screen." src="https://cdn-images-1.medium.com/max/1024/1*Q50lGSWp2yfRvPc1-JAxhQ.png" /><figcaption>Screenshot created by the author</figcaption></figure><p><em>When to use it: I see a lot of value for this, but mostly in modifiers that you can apply to other views. For example, you can use the </em><em>fill modifier and pass a </em><em>Color view to it. This will make another view (e.g. a </em><em>Rectangle) appear in the color that you’ve provided.</em></p><h3>Displaying Text in the Text View of SwiftUI</h3><p>This is the SwiftUI equivalent of UIKit’s Label. It’s used to display text. We saw it before when we created our project and had nothing except a “Hello World!” text with a padding modifier.</p><p>Let’s re-add a Text view with the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c4306bee343ead04014474310c38792/href">https://medium.com/media/0c4306bee343ead04014474310c38792/href</a></iframe><p>This should result in the following preview:</p><figure><img alt="The SwiftUI Text view that contains the text ‘Hello, Better Programming readers!’ that is displayed in the preview canvas of Xcode." src="https://cdn-images-1.medium.com/max/1024/1*TSot2l4-5_lUFWWJ__Ba3A.png" /><figcaption>Screenshot created by the author</figcaption></figure><p>Like the Color view, the Text view comes with a lot of useful initializers. You have initializers for dates and even one for localized strings!</p><p>The latter is really great not only in production, but it can also be tested directly in the preview canvas. As this requires a multi-step process, it is beyond the scope of this article. However, I highly recommend reading the following article in which a localized string is used in the SwiftUI preview:</p><p><a href="https://medium.com/better-programming/a-deep-dive-into-swiftui-previews-66d53469ee43">A Deep Dive Into SwiftUI Previews</a></p><p><em>When to use it: Much like </em><em>Labels in UIKit, the </em><em>Text view will be one of the most used views because we often have to display text in our apps. It is simple yet powerful when you think of the support for features like localized strings and dates.</em></p><h3>Let the User Enter Text via TextField, SecureField, and TextEditor</h3><p>We often display text to provide the user with information. However, apps are not uni-directional from an information standpoint. We often want our users to provide data to us.</p><p>We usually have forms for this, and it doesn’t matter if we’re talking about a simple login mask or a rather complex ticket creation form. We always want to get information from the users and provide them with controls that are the best fit for the current situation.</p><p>One of the most basic input types is text fields. The user can write text in them. To see this in action, replace the content of the body property with the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/624e3f2d26d9be13616f732d359b9fb0/href">https://medium.com/media/624e3f2d26d9be13616f732d359b9fb0/href</a></iframe><p>There are a few things going on here. First, we need a @State binding for the TextEditor to work. Actually, we have bindings for all types of text fields, but the TextEditor is the only one that didn’t work for me with a .constant binding.</p><p>Then we have another type of view with the VStack (stacks are well beyond the scope of this tutorial because they are so powerful and need some deeper level of explanation). The VStack is simply a container that aligns its content vertically.</p><p>We have three types of text inputs. TextField is a single-line text input. You can compare this to the &lt;input type=&quot;text&quot;/&gt; of HTML. The first parameter is the placeholder, while the second is the binding that can be used to make the connection between your code and the visual presentation.</p><p>The SecureTextField, on the other hand, is perfect for confidential information (e.g. passwords). It replaces the characters with dots when the user types the text in. The HTML equivalent would be &lt;input type=&quot;password&quot;/&gt;. The parameters are the same as for a normal text field.</p><p>Lastly, the TextEditor is a multi-line text input that you can compare to the HTML &lt;textarea/&gt; element. It has only one parameter for the binding.</p><p>I recommend that you start the app in the simulator to test it out. Below, you can see it in action with some input from me:</p><figure><img alt="Different SwiftUI text input types like TextField, SecureField, and TextEditor displayed on a iPhone screen." src="https://cdn-images-1.medium.com/max/1008/1*zrcR-2CTHoOJbNUGs03tKw.png" /><figcaption>Screenshot created by the author</figcaption></figure><p><em>When to use them: Text input types are great when the user needs to insert some kind of value that cannot be specified further. Usernames, passwords, comments, or any kind of freeform text are great examples.</em></p><p><em>They will definitely play a big role and you should get used to them. Make sure to pick the right ones for the task at hand. A password shouldn’t use a regular </em><em>TextField and neither should a multi-line text.</em></p><h3>Go Further Than Text With More SwiftUI Controls</h3><p>In many scenarios, text input isn’t the best control for a user to provide certain information. If the user should select a color or give you a yes-or-no answer, you shouldn’t use text inputs if you want to provide a good user experience.</p><p>iOS and SwiftUI provide us with some great alternatives that we’ll now look at briefly.</p><p>Replace the ContentView with the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a480eebba62b3e069e00633363036ac8/href">https://medium.com/media/a480eebba62b3e069e00633363036ac8/href</a></iframe><p>The result should look similar to this:</p><figure><img alt="Many different SwiftUI form views displayed on the screen of an iPhone. It contains a Stepper, Slider, Picker, DatePicker, ColorPicker, and Toggle." src="https://cdn-images-1.medium.com/max/640/1*VOb-Mzyq9xQd6ex8BO0LLQ.png" /><figcaption>Screenshot created by the author</figcaption></figure><p>Let’s discuss them one by one.</p><h4><strong>Toggle</strong></h4><p>The toggle is a perfect fit for yes-or-no settings. The first parameter is used as a label and the second one is the binding that can be used to make the connection to your code.</p><h4><strong>Slider</strong></h4><p>The slider is perfect for closed number ranges that the user can configure. For a vocabulary app, that could be how many words the user wants to learn per day. It should have a minimum and maximum value (a closed range) in order to work correctly.</p><p>There are different initializers that can be used. The one you see above takes a binding so you can access the value in code, a closed range of values that are allowed (0 to 30), a view for the minimum and maximum label, and another label.</p><p><em>Note: Why do we have two </em><em>Text views that display the value of the slider? The first one will only be displayed for some slider subclasses. However, according to Apple’s docs, it is used for accessibility reasons. The latter is used to really display the value for our example.</em></p><blockquote>“A `View` that describes the purpose of the instance. Not all slider styles show the label, but even in those cases, SwiftUI uses the label for accessibility. For example, VoiceOver uses the label to identify the purpose of the slider.” — <a href="https://developer.apple.com/documentation/swiftui/slider/init(value:in:step:oneditingchanged:minimumvaluelabel:maximumvaluelabel:label:)?changes=late__8_6_8_7">Apple’s docs</a></blockquote><h4><strong>Stepper</strong></h4><p>The stepper is similar to the slider but more appropriate when the user will increment or decrement the numbers less drastically and the values are integers.</p><p>It also doesn’t need to be a closed range. However, it doesn’t make sense to use this control when the user has to change the value from -100 to 3,131 because they need one tap for each step.</p><p>The initializer that we’ve used above takes a value that conforms to the StringProtocol for the label and a binding. For the label, as you can see above, you can even use the current value of the stepper as well. That’s the case for all controls.</p><h4><strong>Picker</strong></h4><p>The picker is very interesting because it allows you to select from several different values. It obviously makes sense for all information that can be described with a set of possible values.</p><p>However, when the number of options becomes large, make sure that you sort the values so the user can quickly find the value they are looking for.</p><p>There are different initializers, but the one I’ve used takes the current value as a binding, a label, and the possible values. In this case, it works with tags. When you change the value, the new tag is used to update the binding.</p><h4><strong>DatePicker</strong></h4><p>The date picker is a great input control when the user has to select a date and time. You can configure it heavily, but in our case, we just used the initializer with a label and a binding.</p><h4><strong>ColorPicker</strong></h4><p>This control is perfect for any color input the user needs to make. As soon as you have some form of image or graphic editing, the ColorPicker will be needed.</p><p>The initializer that we’ve used takes a label and a binding.</p><p><em>When to use them: All of these controls are situational but pretty common on iOS. I think the color picker will be rarely used because not all apps require the user to input color values.</em></p><p><em>On your journey to SwiftUI mastery, you should still learn how to use all of them.</em></p><h3>Display Images With the Image View of SwiftUI</h3><p>SwiftUI’s equivalent of UIKit’s UIImageView is simply called Image. It does what you would expect and shows icons or images to the user.</p><p>Apple has recently introduced <a href="https://developer.apple.com/design/human-interface-guidelines/sf-symbols/overview/">SF Symbols</a>. It is a collection of icons that you can use within your app without needing to include them in your assets. You just have to make sure that the icon you want to use is available in your current minimum deployment target.</p><p>Let’s use one of their icons in our app. Imagine that we want to build an e-commerce app that needs a shopping cart. You can open the <a href="https://developer.apple.com/sf-symbols/">Mac App for the SF Symbols</a> and search for “Cart” or select the “Commerce” section in the sidebar.</p><figure><img alt="The SF Symbols app with the commerce section selected." src="https://cdn-images-1.medium.com/max/1024/1*FkSVq2DfwavdlJDyOGRJJA.png" /><figcaption>Screenshot created by the author</figcaption></figure><p>We will use the regular “cart” icon. In order to do so, change the ContentView struct to the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c6dcfe779cbb7b6c30409fd6ad59112/href">https://medium.com/media/7c6dcfe779cbb7b6c30409fd6ad59112/href</a></iframe><p>Your preview should look like this:</p><figure><img alt="The code of the ContentView struct with the Image view on the left and the visual presentation of an iPhone with the cart icon on the left." src="https://cdn-images-1.medium.com/max/1024/1*SqkmskYiC9RleH_5bUO0cw.png" /><figcaption>Screenshot created by the author</figcaption></figure><p>There is an initializer for SF Symbols that accepts a parameter called systemImage. For your own icons or images, you can use the initializer Image(name:). In order to make the image take up the whole space of the frame, you have to use the resizable modifier.</p><p>The size and the alignment are probably subpar for you, but that should give you enough information to get started with images.</p><p><em>When to use it: As with </em><em>Text, the </em><em>Image view will be used heavily. You can use it to show a user image, icons, or thumbnails.</em></p><h3>Let the User Trigger Actions via Button, Menu, Link, and NavigationLink</h3><p>For 99% of iOS apps, we can’t only have a single screen that we show all the time. The user wants to navigate into subviews or show other information depending on their selection.</p><p>That’s where Menu, Link, and NavigationLink come to the rescue.</p><p>Menu allows us to display a menu of options to the user that they can pick from.</p><p>Link allows you to open a URL that usually then opens Safari but could also deep-link into another app.</p><p>NavigationLink is used for the navigation inside your app. You can combine this with the List view to open detail pages for list items.</p><p>Replace the current implementation of ContentView with the following and run the simulator to see the different views in action:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ed9d17cdda1e0ef863dd19584c8e05b/href">https://medium.com/media/9ed9d17cdda1e0ef863dd19584c8e05b/href</a></iframe><p>Below, you can see a video demonstrating what should happen with each click. The Menu is harder to visualize, but you can try it on your own. You should see the print statements in the console:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FQRw9RAQ_OnE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DQRw9RAQ_OnE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FQRw9RAQ_OnE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bdf53708d63ad0639abbaa13f0d6440/href">https://medium.com/media/3bdf53708d63ad0639abbaa13f0d6440/href</a></iframe><p>The Menu gets the title of the control passed as the first argument. It also takes different views as the content. You could technically use a simple Text view as content, but then you wouldn’t have the option to do anything upon user selection. That’s why we used Buttons here.</p><p>The Link is used to open the publication page of Better Programming. In this case, it simply opens it in Safari. It takes as parameters the text for the label that should be displayed as well as the URL that should be opened.</p><p>Lastly, we’ve created a List view that contains three NavigationLinks. The first parameter destination takes the view that should be opened. In this case, we open a view that contains nothing but text. You could replace that with any subview that you’re going to build.</p><p>The label expects a view (in this case, a Text view that gets used, well, as the label for the NavigationLink).</p><p><em>When to use them: Whenever you want to open other views or apps, you can make use of these basic controls. You could also programmatically open other views, but the easiest way is through </em><em>NavigationLink and </em><em>Link. </em><em>Menu is great for context menus where the user can trigger one of several actions.</em></p><h3>Where To Go From Here</h3><p>This guide was intended to give you a broad overview of the available views in SwiftUI. There are many other great views like ProgressView to display the progress of a task or Label, which allows you to show an icon and text side by side (quite common in lists).</p><p>List itself was only covered slightly, even though it plays an important role in iOS development, as most apps consist of many lists. Stacks are another important part of SwiftUI that you should look at. I’m going to write articles that will cover both stacks and lists in detail.</p><p>Lastly, we only scratched the surface of the views that I’ve presented to you.</p><p>That’s why my recommendation is that you read the <a href="https://developer.apple.com/documentation/swiftui/views-and-controls">Apple documentation</a> about the built-in views. Also, make sure to study these views and try to build an app or two consisting of the elements above.</p><p>The SwiftUI views are pretty easy to use and yet also very powerful and have a lot of customization options. The more you play around with them, the more fun it will be and the better you will get at picking the right control for the task at hand.</p><p>Have fun and thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=374ea7549bf9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/an-overview-of-built-in-swiftui-views-374ea7549bf9">An Overview of Built-In SwiftUI Views</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[A Deep Dive Into SwiftUI Previews]]></title>
            <link>https://medium.com/better-programming/a-deep-dive-into-swiftui-previews-66d53469ee43?source=rss-3c34554675f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/66d53469ee43</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Manuel Djirlic]]></dc:creator>
            <pubDate>Mon, 01 Feb 2021 19:22:40 GMT</pubDate>
            <atom:updated>2021-02-01T19:22:40.210Z</atom:updated>
            <content:encoded><![CDATA[<h4>Develop your SwiftUI views faster by utilizing the powerful preview feature</h4><figure><img alt="A smartphone screen displaying a number of apps." src="https://cdn-images-1.medium.com/max/1024/0*73B3PFU4oVtxREmc" /><figcaption>Photo by <a href="https://unsplash.com/@davidgrdm?utm_source=medium&amp;utm_medium=referral">David Grandmougin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>With the release of SwiftUI, Apple hasn’t just provided us with a new beautiful and lightweight API to create user interfaces but also has introduced Xcode Previews.</p><p>We can now have our view code and its visual presentation side by side. Both sides are synced, and changes on either side will result in an update on the other.</p><p>Obviously, the biggest benefit of Xcode Previews is that we don’t have to rebuild our project every single time. Before Previews were introduced we had to start the simulator over and over again, even for the smallest changes.</p><p>A typical scenario for me has been the following:</p><ol><li>I create a user interface with a UIStackView.</li><li>I run the app on the simulator.</li><li>I wait 20 seconds until the app’s started.</li><li>I navigate through the whole app to access the UIViewController that contains my UIStackView.</li><li>It looks awful. I realize I haven’t set the distribution to fillEqually.</li><li>I go back to the code or the interface builder and set the property accordingly.</li><li>I run the app on the simulator again.</li><li>I wait 20 seconds until the app’s started.</li><li>I navigate through the whole app to access the UIViewController that contains my UIStackView.</li><li>Now everything works.</li></ol><p>You can see that was a tedious process that caused a lot of waiting and navigating through the application.</p><p>With SwiftUI Previews, you can omit most of the tasks above. You simply start your preview and make the changes while seeing their impact immediately next to your code editor.</p><p>This article will cover SwiftUI or Xcode Previews by starting with the basics and then slowly getting to more advanced topics like displaying UIViewControllers or localizing your previews.</p><p>We’ll build a small project that you can use as a reference later.</p><h3>Set Up the Project for This Article</h3><p>Before we can preview anything, we need a project. Open Xcode, and on the Welcome to Xcode screen, select “Create a new Xcode project.”</p><figure><img alt="The Welcome to Xcode screen with the option to create a new Xcode project." src="https://cdn-images-1.medium.com/max/1024/1*Vyp0vtwBwEkchBS3OyKwIg.png" /><figcaption>Photo created by the author</figcaption></figure><p>On the following screen, select the default app template for the platform iOS. Then click “Next.”</p><figure><img alt="The template selection of an Xcode project with the iOS tab and the App template highlighted." src="https://cdn-images-1.medium.com/max/1024/1*xMhJu32WSrnb9B4pK8OhOg.png" /><figcaption>Photo created by the author</figcaption></figure><p>For the title, you can choose whatever you like — I’m going to use BudgetPreview. Before you click “Next” again, make sure you’ve set the interface to “SwiftUI” and the life cycle to “SwiftUI App.” Unselect “Use Core Data” and “Include Tests.” We won’t need them for this article.</p><figure><img alt="The option selection of the Xcode project we are going to work on through this tutorial. SwiftUI is chosen as the interface." src="https://cdn-images-1.medium.com/max/1024/1*S8sR8843cVRv-y3GGWN-GQ.png" /><figcaption>Photo created by the author</figcaption></figure><p>Lastly, click “Next,” and select a location where your project should be stored on your file system. Then hit the “Create” button.</p><p>If you haven’t before, you have now successfully set up your first SwiftUI project, and the SwiftUI view named ContentView should be open.</p><p>Let’s dive into the preview feature.</p><h3>How To Use SwiftUI Previews in General</h3><p>If the file ContentView.swift is open, you should now see the following screen.</p><figure><img alt="The ContentView.swift file with the SwiftUI code on the left and the canvas on the right." src="https://cdn-images-1.medium.com/max/852/1*IQuZ7QPiEJA0TKAsueAf-Q.png" /><figcaption>Photo created by the author</figcaption></figure><p>On the left-hand side is the code editor that you know from UIKit projects. On the right side is the interesting part for this article: the preview section.</p><p>If you don’t see the canvas on the right or you simply need more space to work within the code, you can show and hide the preview with this neat shortcut.</p><pre>Option + Command + return (⌥ + ⌘ + ↩)</pre><p>So far, you probably don’t see a preview on the right. That’s because you need to start/resume the preview feature. This is also required if you wrote completely invalid code that caused the preview to crash.</p><p>You can resume by pressing the “Resume” button next to “Automatic preview updating paused.”</p><figure><img alt="The ContentView.swift file with the ‘Resume’-button of the canvas highlighted that you can press to resume the preview." src="https://cdn-images-1.medium.com/max/1024/1*IRlHouU37MfvGOww6bbH3w.png" /><figcaption>Photo created by the author</figcaption></figure><p>Alternatively, and because that can happen a few times per hour, I’d highly suggest you learn the shortcut for this.</p><p>In order to resume the preview, simply use:</p><pre>Option + Command + P (⌥ + ⌘ + P)</pre><p><a href="https://medium.com/better-programming/xcode-8-swiftui-keyboard-shortcuts-that-will-make-you-even-faster-bc3967b75224">Xcode: 8 SwiftUI Keyboard Shortcuts That Will Make You Even Faster</a></p><p>Your preview should look pretty much the same as this one:</p><figure><img alt="The ContentView.swift file with the preview resumed showing the text ‘Hello World’ on an iPhone." src="https://cdn-images-1.medium.com/max/1024/1*MZU1nKQxkP7QOJ-gYBzBXw.png" /><figcaption>Photo created by the author</figcaption></figure><p>There is one more feature I want to show you before we really get into previewing real views that we’ve built. You can start a live preview. This will take a little bit more time to build and sadly doesn’t have a shortcut. Instead, you have to click the run icon in the preview.</p><figure><img alt="The ContentView.swift file with the button for the live-preview highlighted in the canvas." src="https://cdn-images-1.medium.com/max/1024/1*zekEnTrx51dpDNJYqg4-MQ.png" /><figcaption>Photo created by the author</figcaption></figure><p>The live preview has one benefit compared to the regular preview. You can also make interactions with the UI — e.g., click a button, and your tap handling code will fire. That’s a cool thing if you want to know if your button click handling works.</p><p>Yet, for 99% of the cases, you either use the regular preview to see your UI or run the app in the simulator to test button taps. Nevertheless, it’s still something that’s nice to know.</p><h3>Fill the SwiftUI Preview With Data</h3><p>Now with the active preview on the right and our code on the left, let’s make some changes to really see how the preview works.</p><p>Make the following modifications to your ContentView class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2afadfe4d12c68f1b44bfbbe51070e1d/href">https://medium.com/media/2afadfe4d12c68f1b44bfbbe51070e1d/href</a></iframe><p>In the code above, we add a binding that we can pass from the outside into our view. We display the value of the binding in the Text view and use a format specifier to show it as a dollar value.</p><p>In order to fill the preview with data, we have to provide the binding in the struct ContentView_Previews that conforms to the PreviewProvider protocol.</p><p>In the computed property previews, we provide all of the previews we want to display.</p><p>For the sake of this tutorial, we simply passed a constant value as the binding, which is quite common when using previews.</p><p>After those changes, you’ll notice that the preview can’t be resumed. The reason is we’ve set everything correctly in the file but have a compiling error somewhere else in the project.</p><p>Therefore, make sure you also add the new parameter moneyLeft to the BudgetPreviewApp.swift file. You can simply copy and paste the ContentView that we’ve used for the preview.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34a740152533391536acf3a08f0652fa/href">https://medium.com/media/34a740152533391536acf3a08f0652fa/href</a></iframe><p>After that, navigate back into your ContentView and resume the preview. Now, you should see a nicely formatted dollar value in the middle of the screen.</p><figure><img alt="The ContentView.swift file with the preview showing the text ‘$100.12’ in the middle of the iPhone screen." src="https://cdn-images-1.medium.com/max/1024/1*NaZEGOVJfEZ-jDa9L8BqBg.png" /><figcaption>Photo created by the author</figcaption></figure><h3>How To Display Multiple SwiftUI Previews Next to Each Other</h3><p>While previewing a view on one screen size can be helpful for development, it also tricks us into thinking that our view will look great no matter what. The user could use another device or a very large font through dynamic type sizes that would break our layout.</p><p>Don’t worry, the SwiftUI Preview feature’s got you covered. You can display multiple previews in the canvas at the same time. This is possible through the computed property previews of the ContentView_Previews struct. However, it isn’t enough to simply add another preview here.</p><p>Each SwiftUI view needs to have a single root element. The previews property also has an opaque return type of View. That’s why we need to return a single view that wraps multiple previews. We can use the Group view for this.</p><p>Your ContentView_Previews struct should now look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4039f602c0d13e0f09d4ea871953c45/href">https://medium.com/media/b4039f602c0d13e0f09d4ea871953c45/href</a></iframe><p>Now your preview should contain two devices that display the same view.</p><figure><img alt="The ContentView.swift file with two devices side-by-side showing the preview of the SwiftUI view." src="https://cdn-images-1.medium.com/max/1024/1*vFm3X8kxoTB9xNddmqj5Rw.png" /><figcaption>Photo created by the author</figcaption></figure><h3>SwiftUI Preview on Different Devices or Frames</h3><p>Viewing our view two times on the same device type is only helpful if we feed the previews with different input parameters (e.g., very short and very long text).</p><p>But we can even preview our view on different devices. Let’s turn the second preview into an iPad Pro by adding the modifier previewDevice.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fb064151e58a4185edf40268c6225e3/href">https://medium.com/media/5fb064151e58a4185edf40268c6225e3/href</a></iframe><p>This will result in the following representation:</p><figure><img alt="The ContentView.swift file with two devices side-by-side. An iPhone on the top and an iPad on the left showing the previews." src="https://cdn-images-1.medium.com/max/1024/1*DPB7nSbts2VMzHkOTPBgqA.png" /><figcaption>Photo created by the author</figcaption></figure><p>You can get the same result by making the change in the canvas itself. Simply select the preview you want to change in the Attributes Inspector on the right, and change the device. This would generate the same code that we’ve written.</p><figure><img alt="The ContentView.swift file with the option to select the device in the Attribute inspector highlighted." src="https://cdn-images-1.medium.com/max/1024/1*6TqMkIWtxQ2W7i9PqSqxyA.png" /><figcaption>Photo created by the author</figcaption></figure><p><strong>Note:</strong> You can do most of the things I describe in this tutorial via code or directly in the Attribute inspector. In both cases, it’ll change the preview and the code simultaneously. However, I prefer to do the changes via code and will stick to that throughout this article.</p><p>While displaying your views on different devices is a great feature for full-screen views, I dislike it for subviews that’d only take part of the screen. In these cases, I often set the preview to a specific frame size.</p><p>In order to do so, replace the previewDevice modifier with previewLayout and a value of sizeThatFits. This will make the view only take the space that it needs. Afterward, you can provide a specific frame size.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0035d46642f3a1ee688a6b145019bd10/href">https://medium.com/media/0035d46642f3a1ee688a6b145019bd10/href</a></iframe><p>The first preview will always have the size 100x100, while the second uses exactly the space that it needs to fit its content.</p><figure><img alt="The ContentView.swift file with two different previews. One fits the size of the content and the other has a fixed size." src="https://cdn-images-1.medium.com/max/1024/1*LZ3u8Fpm11vPlPi-IN3h2Q.png" /><figcaption>Photo created by the author</figcaption></figure><p>This also allows us to have a better overview of the different previews.</p><h3>Provide Dynamic Type Sizes for Your SwiftUI Previews</h3><p>In iOS, users can change the size of the content. It’s a useful feature, especially for our elders who don’t have the best eyes anymore.</p><p>As developers, we often forget the accessibility of our apps. With the SwiftUI preview, you can easily see how your view would behave if you resize the text.</p><p>Let’s set the dynamic size type to extraExtraExtraLarge. That can be achieved with the environment modifier and the sizeCategory key path.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b755f32803cdc39ac421814e7d34eea/href">https://medium.com/media/3b755f32803cdc39ac421814e7d34eea/href</a></iframe><p>You can immediately see that with this dynamic type, the first preview doesn’t look great anymore. We’ll fix that later.</p><figure><img alt="The ContentView.swift file with two different previews. The one with the XXL text can’t fit the content in one line." src="https://cdn-images-1.medium.com/max/1024/1*gt0woDcb21tnmB6EzaigwQ.png" /><figcaption>Photo created by the author</figcaption></figure><h3>How To Preview Your Views With Dark Mode</h3><p>After the introduction of dark mode in iOS 13, most apps are now expected to support both color schemes, light and dark.</p><p>That’s why you should always make sure you test your views on both settings. The Xcode Preview allows you to do that by simply adding the modifier preferredColorScheme.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24debb836463a59e708885cde9373cc4/href">https://medium.com/media/24debb836463a59e708885cde9373cc4/href</a></iframe><p>This will cause the second preview to show with its dark-mode representation.</p><figure><img alt="The ContentView.swift file with two different previews of the SwiftUI view. One in light and the other in dark mode." src="https://cdn-images-1.medium.com/max/1024/1*pDMKQpELEauhWb9THpwa7g.png" /><figcaption>Photo created by the author</figcaption></figure><h3>Using Different Locales for Your Preview</h3><p>Now you should know the basics of how to set up your previews. That’s why we can dive a little bit deeper into more advanced topics.</p><p>Localization is very important if you want to provide the best user experience to your user all over the world.</p><p>In order to localize our UI, we need to take three steps.</p><ol><li>Add the file with the localized strings (Localizable.strings) to the project.</li><li>Localize the file itself.</li><li>Set up the localization in our Xcode project.</li></ol><p>First things first, create a new file in your project with the following shortcut:</p><pre>Command + N (⌘ + N)</pre><p>Use the template “Strings File,” and name it Localizable.strings.</p><figure><img alt="The Xcode file template selection with the ‘Strings File’ template highlighted." src="https://cdn-images-1.medium.com/max/735/1*L8oGk1Vg3q0zCoSZ6mC6xQ.png" /><figcaption>Photo created by the author</figcaption></figure><p>Now just insert the following key-value pair, but don’t forget the semicolon.</p><pre>&quot;Remaining&quot; = &quot;Remaining&quot;;</pre><p>Then select the file, and in the file inspector, click on the “Localize…” button.</p><figure><img alt="The File Inspector of the Localizable.strings file with the ‘Localize’-Button highlighted." src="https://cdn-images-1.medium.com/max/527/1*hUEV2Qev30WzaZFY-RmK_w.png" /><figcaption>Photo created by the author</figcaption></figure><p>This should create a localized version of the file with only one language (English). The result should look like this:</p><figure><img alt="The File Inspector of the Localizable.strings file with the Localization activated." src="https://cdn-images-1.medium.com/max/515/1*EOh4MXQzOhz9jiv6lTY_Ng.png" /><figcaption>Photo created by the author</figcaption></figure><p>Lastly, we need to add localization to our project. In the project navigator, click on the project, and then select the project once again in the view that pops up. In the info tab is a section called “Localizations.”</p><figure><img alt="Xcode with the project and its info tab selected and the ‘+’-button of the localization section highlighted." src="https://cdn-images-1.medium.com/max/1024/1*ooVr6WRskMBnl3vBwu-cEw.png" /><figcaption>Photo created by the author</figcaption></figure><p>Click the plus button to add a language (I used German, but feel free to pick something else).</p><p>Xcode will ask you which files you want to localize. Select Localizable.strings, and click on “Finish.”</p><figure><img alt="The Xcode menu to choose the resource files that should be localized." src="https://cdn-images-1.medium.com/max/729/1*rCcZhsV4hD0NNjUVdeTyEQ.png" /><figcaption>Photo created by the author</figcaption></figure><p>If everything worked correctly, you should see a little triangle next to the file. When you click on it, it’ll expand, and you should see both language versions for the file.</p><figure><img alt="The Project Navigator of Xcode with the Localizable.strings file expanded to display its different localizations." src="https://cdn-images-1.medium.com/max/272/1*pjUtadQSn_chGSms_AhI1A.png" /><figcaption>Photo created by the author</figcaption></figure><p>Finally, click on the German version. and replace the value of the key-value pair with the words Noch verfügbar.</p><pre>&quot;Remaining&quot; = &quot;Noch verfügbar&quot;;</pre><p>Now that we have a localized text, let’s use it in our view. Navigate back to the ContentView.swift, and wrap our Text view in a VStack. Add another Text view on top of it.</p><p>This new Text view should use the newly created localized identifier. Luckily, Text has another initializer that works with localized string keys. Your ContentView should now look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bf31101928dd2777ced23d20d5fe3a2/href">https://medium.com/media/7bf31101928dd2777ced23d20d5fe3a2/href</a></iframe><p>Our preview won’t change the language by doing this alone. Let’s again use the environment modifier to inject the locale in the second preview. Also, let’s increase the frame size of the first view so it can fit the content.</p><p>This is how your code for the previews should look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42ed33d35fb64fa7fa111321e10f40b9/href">https://medium.com/media/42ed33d35fb64fa7fa111321e10f40b9/href</a></iframe><p>The result in the canvas will contain two previews with different languages.</p><figure><img alt="The ContentView.swift file with two different previews of our SwiftUI view. The first is in English and the second in German." src="https://cdn-images-1.medium.com/max/1024/1*Gdv1VLnFt94Uq6OIyvGlyA.png" /><figcaption>Photo created by the author</figcaption></figure><h3>Previewing UIViews and UIViewControllers With SwiftUI Preview</h3><p>While SwiftUI has evolved greatly and already supports many features that we know from UIKit. It still hasn’t caught up on all the things that we were able to do before.</p><p>We also sometimes have legacy code or frameworks that aren’t converted to SwiftUI.</p><p>In those cases, it’s great that we can switch between SwiftUI and UIKit views easily. We can open UIViewControllers from SwiftUI and SwiftUI views from UIViewControllers.</p><p>That’s not all! We can even use the preview feature for our UIKit views and view controllers.</p><p>In order to see that in action, add a UIViewController to the project. Use the shortcut again to create a new file.</p><pre>Command + N (⌘ + N)</pre><p>This time, select the “Cocoa Touch Class” template.</p><figure><img alt="The Xcode file template selection with the ‘Cocoa Touch Class’ template selected." src="https://cdn-images-1.medium.com/max/735/1*ImUUFQAo9poAjZL9eoWRzg.png" /><figcaption>Photo created by the author</figcaption></figure><p>In the following dialog, enter the name PreviewViewController, and make sure you set the subclass to UIViewController.</p><figure><img alt="The Xcode file option menu with the subclass UIViewController and the class name PreviewViewController selected." src="https://cdn-images-1.medium.com/max/732/1*MEBTEVq9ypWWru06Rg5TGg.png" /><figcaption>Photo created by the author</figcaption></figure><p>Replace the boilerplate code with the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d60414b84abe18b7e6e02da2e2e1e6ab/href">https://medium.com/media/d60414b84abe18b7e6e02da2e2e1e6ab/href</a></iframe><p>This will add a label in the middle of the screen.</p><p>Now create another file, but this time use the “Swift File” template and call it PreviewView.</p><figure><img alt="The Xcode file template selection with the ‘Swift File’ template selected." src="https://cdn-images-1.medium.com/max/733/1*b0VeA0WgyYOVlydHJq-0cg.png" /><figcaption>Photo created by the author</figcaption></figure><p>In this file, make sure you import SwiftUI. Create a struct, PreviewView, that conforms to the protocol UIViewControllerRepresentable (for UIViews you’d need to conform to UIViewRepresentable), which was added by Apple to create a bridge between UIViewControllers and SwiftUI views.</p><p>You also need to implement the two methods of this protocol to create and update the view controller.</p><p>Lastly, you’ll need to add a PreviewProvider to make your preview work.</p><p>The code should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48e1a92b9195d0b832fea01aed55f28f/href">https://medium.com/media/48e1a92b9195d0b832fea01aed55f28f/href</a></iframe><p>The makeUIViewController(:) method will create the PreviewViewController we need. The update method was intentionally left blank, as we don&#39;t need any updating logic.</p><p>If you resume the preview, the canvas should contain a device with your view controller presented and the label in the middle.</p><figure><img alt="The PreviewView.swift file with the preview of UIViewController that we’ve created before." src="https://cdn-images-1.medium.com/max/1024/1*XHGgg-LfyAUYZYjGlGbLdw.png" /><figcaption>Photo created by the author</figcaption></figure><p><strong>Note:</strong> Both of the @available(iOS 13, *) attributes are only needed if your app supports older operating systems (iOS 12 and below). If you work on a SwiftUI project, then that’s pretty unlikely and you can omit them.</p><h3>Where to Go From Here</h3><p>SwiftUI is rapidly evolving and you have to keep up with the development of this new way of writing user interfaces for the Apple ecosystem.</p><p>If you want to go even further when it comes to previews and build upon your newly gained knowledge, I can warmly recommend two articles to you.</p><p>Antoine van der Lee wrote a <a href="https://www.avanderlee.com/swiftui/previews-different-states/">great post</a> about SwiftUI previews almost a year ago. I especially love his idea about writing a generic preview view that you can wrap around your own previews. With that, you don’t have to create a dark-mode version or the different relevant size types over and over again.</p><p>One guy who always has great ideas about Swift and iOS development is John Sundell. He even created a static-site builder with Swift to build his own website. <a href="https://www.swiftbysundell.com/articles/getting-the-most-out-of-xcode-previews/">In his article</a> about Xcode Previews, he shows many of the great extensions you can use in your own projects.</p><p>It’s worth getting proficient in Previews because it’ll increase our velocity when it comes to building great user interfaces. So I hope this article provided you a solid foundation regarding this topic.</p><p>I wish you good luck and a lot of fun with SwiftUI, Xcode Previews, and programming in general.</p><p>Thanks for your time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66d53469ee43" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/a-deep-dive-into-swiftui-previews-66d53469ee43">A Deep Dive Into SwiftUI Previews</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[The Ultimate Guide to Loops in Swift]]></title>
            <link>https://levelup.gitconnected.com/the-ultimate-guide-to-loops-in-swift-431664155618?source=rss-3c34554675f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/431664155618</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Manuel Djirlic]]></dc:creator>
            <pubDate>Tue, 22 Dec 2020 10:17:56 GMT</pubDate>
            <atom:updated>2020-12-26T14:58:46.638Z</atom:updated>
            <content:encoded><![CDATA[<h4>Master one of the most fundamental building blocks in programming</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8Sn9Lu4iAhXeHoas" /><figcaption>Photo by <a href="https://unsplash.com/@tine999?utm_source=medium&amp;utm_medium=referral">Tine Ivanič</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>All programming languages are unique. They differ at least in some respect from all their peers.</p><p>Swift, for example, has optionals, typealiases, and opaque return types.</p><p>However, there are some basic building blocks that nearly every language uses. Conditionals allow you to run a certain part of your code only if a condition evaluates to true. Most languages use if-clauses to realize this conditional logic.</p><p><a href="https://medium.com/swlh/the-ultimate-guide-to-swift-conditionals-297f17fd5c1f">The Ultimate Guide to Swift Conditionals</a></p><p>But conditionals are not the only basic building block that the majority of programming languages utilize. We have classes, objects, functions, variables, constants, access control, and many more.</p><p>We developers often want to learn new things fast and it’s tempting to look at all those advanced features a language provides us with. With that, we often forget to master the basics first. It’s important to build a solid foundation before we move on. This will then help us acquiring knowledge at a faster pace because we understand the core of the language itself.</p><p>That’s why today I want to cover one of those fundamental pieces in the programming language Swift.</p><p><strong>Loops.</strong></p><p>You will learn the following things while reading this post:</p><ol><li>What are loops?</li><li>The while-loop.</li><li>The repeat-while-loop.</li><li>A recreation of the classic for-loop in Swift.</li><li>The range-based for-in-loop.</li><li>Iterating over sequences with the for-in-loop.</li><li>Alternatives to using loops.</li></ol><p>This article attempts to be the only resource you will need to fully understand all types of loops in Swift. I will add personal recommendations as well as tips and tricks to get the most out of each type of loop. Sadly, I can’t cover every nuance regarding the topic. But after you’ve finished, you will be well prepared for any challenges you will face with loops.</p><h4>What are loops?</h4><p>Loops contain code that is intended to not only run once but multiple times.</p><p>Imagine a world without loops and you would want to print the numbers from 0 to 100.</p><p>You would need to write 100 print-statements! Now think about more dynamic behavior where you want to run certain pieces of code depending on the number of data items the user has. That would be kind of impossible to implement!</p><p>Loops allow you to specify a condition and run some code in as many iterations as it will take to make the condition evaluate to false.</p><p>As an example, let’s assume you get an undefined number of integers from the user, and then you want to double them. With a loop, you can iterate over those numbers and multiply each of them by 2. You write the code once but execute it multiple times.</p><p>There are alternatives to loops like recursion. But more on that later.</p><p>With that more general explanation, let’s look at a concrete example and look at some code to make sense of the theory behind it.</p><h4>The while-loop in Swift</h4><p>If you are lucky like me and have a degree in computer science you will know this type of loop.</p><p>It’s the first loop you will see in many of the typical ‘introduction to programming’ classes. I first encountered it with the language C, and then later on with Java.</p><p>Let’s look at a code example in Swift first before we discuss this further.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4d43b702c7f71827d746e1b30ffc939/href">https://medium.com/media/c4d43b702c7f71827d746e1b30ffc939/href</a></iframe><p>The loop above prints to the console the numbers from 10 to 0 (including 10 and 0).</p><p>The while-loop basically does the following:</p><blockquote>Run this piece of code if the condition evaluates to true and as many times as this condition evaluates to true.</blockquote><p>The variable countdown is used for the condition part of the while-loop. In the first iteration, the value is 10 and, therefore, the code inside the while-block gets executed.</p><p>At the end of the block, the variable countdown will be decremented by 1. So it’s 9 in the next iteration.</p><blockquote><strong>Note: </strong>Don’t forget this last line of code! One of the easiest mistakes that you can make regarding loops, is to forget to change the variable that is used for the evaluation. Without the last line of the while-block, we would execute the code an unlimited amount of times. Each and every iteration the variable countdown would be 10. It would cause our apps to freeze and ultimately crash.</blockquote><p>The loop will be executed as long as the condition evaluates to true, in this case as long as the variable countdown is greater or equal to 0.</p><p>As soon as the condition evaluates to false (countdown becomes less than 0) the while-block will not be executed anymore and we will continue with the code that follows the loop.</p><p>There are two more things I want to point out here:</p><ol><li>It doesn’t matter where inside the block you change the variable that is used for the condition. The current iteration will run until it’s finished and then check the condition before the next iteration. Changing the variable, therefore, is not acting like a break-, continue- or return-statement. <strong>However, it does matter if you want to use it inside the following code!</strong></li><li>You don’t have to use a counter as I did. It’s the most common scenario, but you can also use everything else that can be used for a condition. For example, you could also use a variable that is true at the beginning and turns false when something happens inside the loop.</li></ol><p><strong>Relevance:</strong> Personally, I don’t use the while-loop often anymore. When you come to Swift from an older programming language you may tend to use it quite regularly. But there is a major downside to the while-loop. You have to change the variable that influences the condition on your own! If you forget about it or do a mistake, the loop will run endlessly. Swift is trying its best to avoid such human errors and that’s why I think other loops are a better fit for Swift and your apps.</p><h4>The repeat-while-loop in Swift</h4><p>You probably know this type of loop as well. Usually, it is known by a different name. The do-while-loop.</p><blockquote><strong>Note:</strong> In the early days of Swift, this was also called do-while. They changed the naming convention to repeat-while in Swift 2.0.</blockquote><p>It is pretty similar to the while-loop but behaves differently on the first iteration. Let’s look at another example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20dde161e736ad221043dcc9c151295e/href">https://medium.com/media/20dde161e736ad221043dcc9c151295e/href</a></iframe><blockquote><strong>Note: </strong>In both examples, we haven’t used the increment or decrement operators (e.g. howManyIterationsLeft--, --countdown). These operators don’t exist in Swift anymore and were deprecated in the language version 2.2.</blockquote><p>Can you guess how often this loop will run? You may assume that it won’t run at all as the condition says that howManyIterationsLeft needs to be greater than 0.</p><p>That’s the catch with the repeat-while-loop. It will always execute at least once! In the above code snippet, the value of the variable howManyIterationsLeft will be printed to the console. In that case, it’s 0.</p><p>The repeat-while-loop basically does the following:</p><blockquote>Run this piece of code and after each iteration check if the condition still evaluates to true. If that’s the case continue with another iteration.</blockquote><p>So let’s recap on the differences between the while- and the repeat-while-loop.</p><p>While-loop:</p><ol><li>Evaluates the condition before it runs an iteration of the loop.</li><li>Runs between 0 and endless times.</li></ol><p>Repeat-while-loop:</p><ol><li>Evaluates the condition after it runs an iteration of the loop.</li><li>Runs between 1 and endless times.</li></ol><p><strong>Relevance:</strong> The while-loop and repeat-while-loop are equally often seen in Swift. The repeat-while-loop is maybe even less used due to the fact that it checks after the first iteration and this is rarely useful. Both share the disadvantage of having to remember to correctly change the variable that is used for the condition. If you make a programming mistake here, it comes at the cost of having a crashing app. To me, it just seems error-prone and that is not what Swift is all about.</p><h4>A recreation of the classic for-loop in Swift</h4><p>That’s the last type of loop that nearly every programming language has. But Swift has no real support for this. The classic for-loop in many programming languages includes the following pieces:</p><ol><li>An initialization statement.</li><li>A condition.</li><li>An increment/decrement.</li></ol><p>Let’s first look at an example in C.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d2e56353fe28a18e8011f4e51239504/href">https://medium.com/media/1d2e56353fe28a18e8011f4e51239504/href</a></iframe><p>The initialization statement is int counter = 1. Separated by semi-colons we then have the condition and after that the incrementation of the variable that is used for the condition.</p><p>We still have to take care of changing the condition variable ourselves, but the syntax forces us to remember it.</p><p>Swift doesn’t provide such a for-loop but we could recreate it with the <a href="https://developer.apple.com/documentation/swift/1641347-stride">stride</a> function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2aa199e3f7146f01c4880477b1bebafa/href">https://medium.com/media/2aa199e3f7146f01c4880477b1bebafa/href</a></iframe><p>It’s actually already a for-in-loop, but I wanted to show you the more classy variation first.</p><blockquote><strong>Note:</strong> Be careful, the stride function doesn’t include the end of the sequence (the second parameter to). Therefore, we have to pass 11 in order to print the values from 1 to 10.</blockquote><p><strong>Relevance:</strong> I want to be honest with you, I haven’t seen or used the for-in-loop with the stride function in more than 6 years of Swift programming. If you want to forget one piece of information from this post, then it’s obviously this solution. The only reason I see for this is when you want a different increment than 1. You could pass 2, -5, or 10 to the by parameter. Nonetheless, Swift has a far more common loop type that we want to look at next.</p><h4>The range-based for-in-loop in Swift</h4><p>We’ve looked at many available options and the relevance of them all was pretty low. Swift provides us with a for-in-loop that can take many different shapes and is definitely the most important of all loop types.</p><p>Let’s start with a loop where we are only interested in the index or a counter again. This time it is in a more Swifty-way.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efaa6a74cacb57dc32fb54fa2d483a90/href">https://medium.com/media/efaa6a74cacb57dc32fb54fa2d483a90/href</a></iframe><p>It’s so much easier to read and does exactly what you would think. It iterates over the range we provided including the lower and upper bound. In the example above it would iterate over the numbers from 1 to 10 and print all of them to the console.</p><p>I’ve already told you that the for-in-loop in Swift is very versatile. So can we also exclude the upper bound?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de06357ade019e48188ff1b40a2e6e45/href">https://medium.com/media/de06357ade019e48188ff1b40a2e6e45/href</a></iframe><p>The console would see the numbers from 0 to 59.</p><p>As you can see, the half-open range operator (..&lt;) works in Swift loops, too. You can even use constants or variables for the range operator.</p><p>Again we don’t have to handle the counting up on our own.</p><p>How about decrementing in the for-loop?</p><p>You can simply reverse the range like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c162549289573425cd53791d4f733633/href">https://medium.com/media/c162549289573425cd53791d4f733633/href</a></iframe><p>This will still print out the numbers of 0 to 59. But in reversed order, so exactly what we were looking for.</p><p><strong>Relevance: </strong>I don’t use this method daily as there is an even more common solution that we look at next. Besides that, I think you should know how to use this variation of the for-in-loop as you will need it from time to time. I tend to use it 2–3 times per month and in these situations is good to know.</p><h4>Iterating over sequences with the for-in-loop</h4><p>Now let’s look at the solution I use the most when it comes to loops in Swift.</p><p>Therefore, let’s first understand what we do most of the time in programming with loops.</p><p>Why do we loop in the first place? Most of the time it’s because we want to do an operation over and over again on a certain number of elements that oftentimes come from external sources (e.g. user input or network request).</p><p>We could now get the number of elements and then use the index-based solution above. Let’s see that in code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bda9e9e91c142200d669ee0642c0b6ae/href">https://medium.com/media/bda9e9e91c142200d669ee0642c0b6ae/href</a></iframe><p>In the code snippet above, we have 3 animals. We iterate over them with an index and access the element at the index of the array and print it out with string interpolation.</p><p>However, that is still error-prone. Imagine, we would have accidentally used the following range:</p><pre>1..&lt;animals.count</pre><p>That would cause us to not print dog to the console. Or how about that:</p><pre>0...animals.count</pre><p>That would even crash our app as we try to access an element at an index that is not available.</p><p>Sure, all of that is of less severity when it comes to printing out values. Anyway, the same applies to critical business logic like transfers from one bank account to another. It is a problem when you don’t apply a currency exchange rate on one of the transactions.</p><p>So let’s revisit the example above with a better approach.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38438db2b35bcca6335aa9d533ea1dcf/href">https://medium.com/media/38438db2b35bcca6335aa9d533ea1dcf/href</a></iframe><p>That looks nicer! But how does it work? It actually iterates over the sequence (in this case an array) and creates a constant of those values for each iteration that we can then use inside the loop.</p><p>We don’t need to handle indices here. We can simply use the element.</p><p>How does that work with dictionaries? Here is the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa52a9ad7568deb9d5c3aa41b5eb3418/href">https://medium.com/media/aa52a9ad7568deb9d5c3aa41b5eb3418/href</a></iframe><p>You can see, that we use the same loop but this time, we can access the key of the animal with the key and the value with the value property.</p><blockquote><strong>Did you know:</strong> You can actually use emojis in Swift. You can even go that far that you use them as variable names, but I would recommend avoiding that. It makes it harder to access them.</blockquote><p>I will omit <a href="https://developer.apple.com/documentation/swift/set">Sets</a> as they work the same as arrays from a loop perspective. You simply need to know, that sets have no duplicates. But be careful! They are also not ordered! That can have some unintended side effects.</p><p>But what if you still need the index of the elements? What if you want to print out something like <em>0: Dog</em>, <em>1: Cat</em>, <em>2: Fish</em>? Or for any other reason, you also need to know the index of the element?</p><p>The for-in-loop is pretty versatile and got a solution for that, too! You can use the function <a href="https://developer.apple.com/documentation/swift/enumeratedsequence">enumerated</a> on the array and access the index as well as the element.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c119a95b8e60851b135ce052ced6eb3b/href">https://medium.com/media/c119a95b8e60851b135ce052ced6eb3b/href</a></iframe><p>The enumerated function will create a tuple with the structure <em>(n, x) </em>where <em>n</em> is the index of the element starting from zero and <em>x</em> is the element itself.</p><p>With that, we can get access to the index alongside the actual element and use both of these values in the same loop without the need to alter the index or access the original elements array.</p><p><strong>Relevance:</strong> I’ve already mentioned that I prefer this loop in that variation by far over all other loop types. It’s very versatile and you can access the index as well as the element or both at the same time. Make sure that you get used to the syntax because you will see it over and over again.</p><h4>Alternatives for using loops in Swift</h4><p>There are two alternatives, that you should know about when it comes to loops.</p><p><strong>Recursion:</strong></p><p>First, there is recursion. Recursion means you have a function that calls itself but with different input parameters. Through that, you can create a loop without actually having a loop.</p><p>Let’s look at a code example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06509615793caa57752a9d9e9aad9fa1/href">https://medium.com/media/06509615793caa57752a9d9e9aad9fa1/href</a></iframe><p>We call the printAnimal function only once (in line 12). However, it will still print out all animals by calling itself. It stops when we reached the last index of the animals&#39; array and simply prints out its value. You see that there is no loop.</p><p><strong>Relevance:</strong> To me, recursion is harder to grasp and to think about. It makes sense to challenge ourselves from time to time and try different ways to solve a common problem. This broadens our mindset and makes us open to new solutions. Anyway, in production code, I tend to use loops over recursion.</p><p><strong>Higher-order functions:</strong></p><p>The second alternative is more common these days. With the rise of functional programming, also an alternative to loops has emerged in form of higher-order functions. I can’t cover all of them, but I want to show you one example with the map function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1e26dba6c2a446099f825e4c58b16e0/href">https://medium.com/media/d1e26dba6c2a446099f825e4c58b16e0/href</a></iframe><p>It will actually print out all animals as we did with loops before.</p><p>The map function is useful to transform elements of a collection. Higher-order functions can be chained together one after another and you can even pass functions for the mapping to them.</p><p>If that left you with more questions than answer, I highly recommend this great guide about higher-order functions in Swift:</p><p><a href="https://abhimuralidharan.medium.com/higher-order-functions-in-swift-filter-map-reduce-flatmap-1837646a63e8">Higher order functions in Swift: Filter, Map, Reduce, flatmap, compactMap</a></p><p><strong>Relevance:</strong> As my most recent projects are making heavy use of functional reactive programming (FRP), I also more and more often use these higher-order functions. Anyway, when I’m really struggling to get something to work, I still try to solve it in a loop first before I switch to the higher-order functions. Nevertheless, this is definitely a thing you need to know to call yourself an expert in Swift development.</p><h4>Conclusion</h4><p>That wraps up my guide about loops in Swift. It’s important to really get comfortable with them as you will see them often. No matter, if you are a macOS, iOS, tvOS, watchOS, or any other developer, you will find loops in many projects you get into.</p><p>Even with the rise of functional reactive programming, loops, and especially the idea behind them stays a core building block that you need to understand in order to master your craft.</p><p>Thanks for your time and have fun with loops!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=431664155618" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/the-ultimate-guide-to-loops-in-swift-431664155618">The Ultimate Guide to Loops in Swift</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Xcode: 8 SwiftUI Keyboard Shortcuts That Will Make You Even Faster]]></title>
            <link>https://medium.com/better-programming/xcode-8-swiftui-keyboard-shortcuts-that-will-make-you-even-faster-bc3967b75224?source=rss-3c34554675f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc3967b75224</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Manuel Djirlic]]></dc:creator>
            <pubDate>Mon, 14 Dec 2020 21:10:11 GMT</pubDate>
            <atom:updated>2020-12-14T21:10:11.799Z</atom:updated>
            <content:encoded><![CDATA[<h4>Master Xcode and build apps faster</h4><figure><img alt="Laptop keyboard" src="https://cdn-images-1.medium.com/max/1024/0*6cPaAvwDmvTrjUzF" /><figcaption>Photo by <a href="https://unsplash.com/@mylifeasaryan_?utm_source=medium&amp;utm_medium=referral">Aryan Dhiman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><p>As software developers, we not only love to build applications, but we also love to find and use the best tools available in order to do so.</p><p>As iOS developers, we are very lucky. With Swift, we have a modern programming language in our tool belt. Additionally, Apple released a brand new, modern, and declarative UI framework in 2018 called SwiftUI.</p><p>That means we are well prepared for the future with the instruments we have.</p><p>However, we also love to work efficiently with the technologies we have. One easy way to increase our productivity and get more code written is to use keyboard shortcuts.</p><p>Sadly, there are not that many keyboard shortcuts available for SwiftUI (or they are not documented that clearly). Nevertheless, getting to know the ones that are already available is a good way to prepare for the future while having more time for the things that really matter.</p><p>You can accomplish the following things with keyboard shortcuts:</p><ol><li>Resume the preview feature of SwiftUI.</li><li>Show/hide the preview pane.</li><li>Open the library of controls, modifiers, etc.</li><li>Open the Quick-Actions menu.</li><li>Show the inspectors of the SwiftUI view.</li><li>Get quick access to the attribute inspector of a view.</li><li>Select the preview destination (devices).</li><li>Switch to the previous or next preview destination.</li></ol><p>There are tons of helpful Xcode shortcuts out there that can be used when creating UIKit and SwiftUI views. However, this article will cover the ones that are specific to SwiftUI.</p><h3>1. Resume the Preview Feature of SwiftUI</h3><figure><img alt="Resuming the preview in Xcode for a SwiftUI view with the keyboard shortcut." src="https://cdn-images-1.medium.com/max/640/1*bsLrLCkgYsKmTLuCppWwcQ.gif" /><figcaption>GIF created by the author.</figcaption></figure><p>The preview of SwiftUI views is very powerful. It allows you to make changes to a certain view and see the impact of the changes reflected in the preview pane. You cannot only omit the navigation to the screen in the simulator, but you also don’t need to run the simulator! All it takes is a short time to build it initially, and after that, all changes are visible nearly instantly.</p><p>That alone helps us to become insanely fast while creating SwiftUI views. It also makes a lot of sense because, for modifiers that are applied to SwiftUI views, the order often matters. That could be a reason for several rebuilds and test runs in the simulator.</p><p>However, pretty often you have to start or resume the preview feature. For example, when opening a view, Xcode won’t build it immediately. Instead, it will wait until you explicitly tell it to do so. Also when there are some errors in our SwiftUI code, the preview may break. Sure, you can click on the button to resume the preview, but that takes time and therefore Apple added the following keyboard shortcut:</p><pre>Option + Command + P (⌥ + ⌘ + P)</pre><h4><strong>Relevance</strong></h4><p>In my opinion, this is the most important keyboard shortcut you need to learn. You will need this feature often and therefore save yourself headaches if you start using it today.</p><h3>2. Show/Hide the Preview Pane</h3><figure><img alt="Showing and hiding the preview pane in Xcode with the keyboard shortcut." src="https://cdn-images-1.medium.com/max/640/1*iXV5CetZza2eo3R-u0LTUw.gif" /><figcaption>GIF created by the author.</figcaption></figure><p>I’ve already told you about the neat preview feature of SwiftUI views. However, from time to time, we really want to focus on the code. For me, that often happens when I have the assistant editor open with other code and three editors are just a little too much.</p><p>For you, that could also happen when you are on the road and all that you have is a small MacBook screen. Later, when you have our bigger monitor, you can show the preview pane again. Luckily, it’s the same keyboard shortcut in both cases:</p><pre>Option + Command + return (⌥ + ⌘ + ↩)</pre><p>Bonus: If that is one keystroke too many for simply hiding the preview pane, you can also use the following keyboard shortcut. Be aware, though, that this will only hide the pane and not show it again if hidden.</p><pre>Command + return (⌘ + ↩)</pre><h4><strong>Relevance</strong></h4><p>This is more of a situational keyboard shortcut but definitely a nice-to-know.</p><h3>3. Open the Library of Controls, Modifiers, etc.</h3><figure><img alt="Opening the library in Xcode for a SwiftUI view with the keyboard shortcut." src="https://cdn-images-1.medium.com/max/640/1*TU5ny68zTinw96SNMC9_YQ.gif" /><figcaption>GIF created by the author.</figcaption></figure><p>I’ve already covered modifiers briefly. They make modifications to your SwiftUI view. There are tons of modifiers you need to remember. If you are like me and often forget the name of certain modifiers or colors, Apple has got you covered with the library. You can open and then search the library to find the modifier you are looking for.</p><p>It doesn’t only work for modifiers but also for controls, snippets, media, and even your defined colors! No need to remember smaragdineLight or darkMikado anymore!</p><p>You have probably already used the library in UIKit development to add a view controller to a storyboard or add a button to it.</p><p>Conveniently, Apple uses the same shortcut here:</p><pre>Shift + Command + L (⇧ + ⌘ + L)</pre><p>With that, you can access all the different library areas.</p><p>Bonus: You may open the library with a shortcut but find yourself switching between the tabs (modifiers, controls, etc.) with the mouse again. But that’s actually not needed.</p><p>Use the following keyboard shortcut to switch the tabs to the left:</p><pre>Shift + Command + [ (⇧ + ⌘ + [)</pre><p>And this one to switch the tabs to the right:</p><pre>Shift + Command + ] (⇧ + ⌘ + ])</pre><p>You will find both of these bonus shortcuts over and over again. It’s the common solution to switch between tabs and you probably already use it.</p><h4><strong>Relevance</strong></h4><p>Overall, the keyboard shortcut to open the library in Xcode is pretty heavily used and I think it’s worth the time to get used to it. The option to select colors makes it especially valuable.</p><h3>4. Open the Quick-Actions Menu</h3><figure><img alt="Opening the Quick Actions menu in Xcode for a SwiftUI view with the keyboard shortcut." src="https://cdn-images-1.medium.com/max/640/1*XvX9_7Vn0sH0crAMbeHGNA.gif" /><figcaption>GIF created by the author.</figcaption></figure><p>One of the coolest things about SwiftUI is that it allows different styles of working.</p><p>If you are more of a visual person (maybe you have a design background), you will use the preview pane and build your UI using the library to drag and drop your views onto the canvas.</p><p>On the other hand, if you are more of a techie, you may only use the code to precisely craft the user interface.</p><p>Or maybe you use both and have your own style of working.</p><p>Now comes the best part. Even when you are a team and one member likes to create the SwiftUI views in code and another uses the visual tool, it will produce both! Your canvas and your code will always be in sync!</p><p>And with that, I want to introduce a nice keyboard shortcut that works for all types of developers. You can open the Quick-Actions with the following shortcut:</p><pre>Command + Click (⌘ + Click)</pre><p>The Quick-Actions menu gives you access to all kinds of things you want to do. You can embed your current view into one of the stacks (HStack, VStack, ZStack), a list, or even make a conditional or loop out of it.</p><h4><strong>Relevance</strong></h4><p>The Quick-Actions menu gives you so many options, ranging from adding functionality to refactoring, that we can look over the fact that we have to touch our mouse when using this keyboard shortcut. It’s still very nice — especially for extracting some code into its own method while our code grows larger. Definitely a must-have kind of shortcut.</p><h3>5. Show the Inspectors of the SwiftUI View</h3><figure><img alt="Opening  the inspectors in Xcode for a SwiftUI view with the keyboard shortcuts." src="https://cdn-images-1.medium.com/max/640/1*XvmfLUohqs5au8FGt8iOJw.gif" /><figcaption>GIF created by the author.</figcaption></figure><p>This is another shortcut that we should already know from UIKit. Each SwiftUI view has the following inspectors: the File inspector, History inspector, Quick Help inspector, and Attributes inspector. All of them give us several convenient features regarding our current view.</p><p>The Quick Help inspector, for example, gives us access to parts of documentation about the view we are currently using. That’s helpful when using built-in views like Text, Color, etc.</p><p>Opening a certain inspector is something we need to do quite regularly. Therefore, let’s look at the shortcuts one by one.</p><p>File inspector:</p><pre>Option + Command + 1 (⌥ + ⌘ + 1)</pre><p>History inspector:</p><pre>Option + Command + 2 (⌥ + ⌘ + 2)</pre><p>Quick Help inspector:</p><pre>Option + Command + 3 (⌥ + ⌘ + 3)</pre><p>Attributes inspector:</p><pre>Option + Command + 4 (⌥ + ⌘ + 4)</pre><p>Bonus: If you want to hide the inspectors completely, there is another shortcut:</p><pre>Option + Command + 0(⌥ + ⌘ + 0)</pre><h4><strong>Relevance</strong></h4><p>We’re used to changing the properties of views quite often while working with UIKit. In SwiftUI, we can more easily change the attributes directly in code. Nevertheless, it’s worth knowing the shortcuts to easily access the information. If you are still maintaining some UIKit projects, it may become more valuable.</p><h3>6. Quick Access to the Attribute Inspector of a View</h3><figure><img alt="Opening the attribute inspector in Xcode for a SwiftUI view with the keyboard shortcut." src="https://cdn-images-1.medium.com/max/640/1*Zbpfp4KD3O7X2V2QGBMIlw.gif" /><figcaption>GIF created by the author.</figcaption></figure><p>I’ve already told you that the Attribute inspector in SwiftUI is, in my opinion, less used than before with UIKit.</p><p>However, it still gives us the option to easily change the attributes without the need to know them that well (you don’t have to remember the syntax for the code you need to write). With that said, I want to introduce an alternative way to open the Attribute inspector instead of the shortcut I mentioned before:</p><pre>Control + Option + Click (⌃ + ⌥ + Click)</pre><h4><strong>Relevance</strong></h4><p>Again, this keyboard shortcut works for both the SwiftUI preview pane and the code. It’s a nice way to access the most common attributes of a view. I need more projects to really tell you how often I tend to need this shortcut, but overall, it’s like all the inspector shortcuts before — which is to say of lower value compared to other shortcuts I have shown you.</p><h3>7. Select the Preview Destination (Devices)</h3><figure><img alt="Switching the preview destination in Xcode for a SwiftUI view with the keyboard shortcut." src="https://cdn-images-1.medium.com/max/640/1*bogys_E0tItUug6PqzSg_A.gif" /><figcaption>GIF created by the author.</figcaption></figure><p>This is a very cool shortcut. Unfortunately, Xcode lacks some performance to really make it shine (at least on my MacBook Pro).</p><p>When we design our SwiftUI views, we usually show the preview pane next to it. I’ve shown you how to start/resume the preview with the first shortcut. However, this will only preview the SwiftUI view for the currently selected destination (the destination is visible next to the target at the top of the Xcode. See the image below).</p><figure><img alt="A screenshot of Xcode with the selected destination highlighted." src="https://cdn-images-1.medium.com/max/1024/1*YNOUQU7QS-Mhalsf9r-TCQ.png" /><figcaption>Screenshot by the author.</figcaption></figure><p>From time to time, you may want to not only see your view on the biggest iPhone 12 Pro Max but also see how it looks on other smaller devices. To switch the destination, you can open the destination selection with this neat shortcut:</p><pre>Control + Shift + 0 (⌃ + ⇧ + 0)</pre><p>Sadly, it takes a while to build the preview of the view for the new destination. But at least it saved us some time by avoiding the use of the computer mouse and moving all the way to the top of the screen.</p><h4><strong>Relevance</strong></h4><p>I think we will really appreciate this feature to rapidly change the destination in a few years when our machines get more powerful. For now, it’s cool because we also need it if we want to run the app on a different simulator or device.</p><h3>8. Switch to the Previous or Next Preview Destination</h3><figure><img alt="Switching between several preview destination in Xcode for a SwiftUI view with the keyboard shortcuts." src="https://cdn-images-1.medium.com/max/640/1*b8sR36lSKkjcn-v9A-Q_Ng.gif" /><figcaption>GIF created by the author.</figcaption></figure><p>This is similar to another keyboard shortcut I showed you before. But this time, you don’t have to open the destination menu and select the device you want to see. Instead, this shortcut is helpful when you simply want to see the next destination or the previous one.</p><p>The same restrictions apply for these shortcuts as for the destination menu. It will take some time to rebuild your preview for the new device.</p><p>There are two shortcuts for these actions.</p><p>Previous destination:</p><pre>Control + Shift + Command + [ (⌃ + ⇧ + ⌘  +[)</pre><p>Next destination:</p><pre>Control + Shift + Command + ] (⌃ + ⇧ + ⌘ +])</pre><h4><strong>Relevance</strong></h4><p>You also need some time, but that’s not because of the shortcut itself. Instead, it’s due to the time Xcode needs to rebuild the preview. However, I think this can be tremendously useful when you have two screen sizes you want to look at and wish to arrange your simulators in the list accordingly. In the end, this is not that needed, as you won’t switch between the destinations that often but mostly work on one size and then improve the UI for the other.</p><h3>Conclusion</h3><p>Keyboard shortcuts are a great way to increase our performance, even though it’s more on a micro level of productivity.</p><p>SwiftUI is an amazing framework that lets developers as well as designers rapidly create user interfaces. SwiftUI is only two years old, and it will take more time for it to provide us with all the features that we need.</p><p>Sadly, the same is true for shortcuts. However, the ones that are already available can be helpful and it’s nice to know and really get used to them. In the next few years when Apple releases more and more features and shortcuts, you will be happy that you already know some.</p><p>If I could wish for one more shortcut, I would definitely love one for the live preview. That’s a feature that lets you even click around and perform actions in the canvas without starting the simulator.</p><p>What can you take away from this article? Well, I hope you have learned a few shortcuts that you didn’t know that will make your experience with SwiftUI even better.</p><p>Have I forgotten one neat keyboard shortcut that you know? Let me know! Thanks for your time and have fun with SwiftUI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc3967b75224" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/xcode-8-swiftui-keyboard-shortcuts-that-will-make-you-even-faster-bc3967b75224">Xcode: 8 SwiftUI Keyboard Shortcuts That Will Make You Even Faster</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[SwiftUI in Production? 6 Pros and Cons You Need to Consider]]></title>
            <link>https://medium.com/better-programming/swiftui-in-production-6-pros-and-cons-you-need-to-consider-69ace40a1b46?source=rss-3c34554675f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/69ace40a1b46</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Manuel Djirlic]]></dc:creator>
            <pubDate>Wed, 02 Dec 2020 13:00:14 GMT</pubDate>
            <atom:updated>2020-12-07T21:03:04.877Z</atom:updated>
            <content:encoded><![CDATA[<h4>Should you use SwiftUI or UIKit in your next project?</h4><figure><img alt="abstract pattern made with colored light trails" src="https://cdn-images-1.medium.com/max/1024/0*_q6DmLKnobtTlf-T" /><figcaption>Photo by <a href="https://unsplash.com/@lazycreekimages?utm_source=medium&amp;utm_medium=referral">Michael Dziedzic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>SwiftUI was introduced at WWDC 2018 and has been supported by iOS since version 13.</p><p>Usually, two years are enough for us, the iOS developer community, to start using a feature in production code. However, for really big changes, like moving from <a href="https://en.wikipedia.org/wiki/Objective-C">Objective-C</a> to Swift or now from UIKit to SwiftUI, a little more analysis is required.</p><p>Here are 6 cons and 6 pros that will help you make a profound decision for your next or current iOS project.</p><p><strong>Cons:</strong></p><ol><li>Users on older operating systems can’t use your app.</li><li>Problems will be harder to solve as no one faced them before.</li><li>There are some features that are only available in UIKit so far.</li><li>It will take more time because you are not that familiar with the toolkit.</li><li>Other developers in your team may not know SwiftUI.</li><li>Best practices are not yet formed.</li></ol><p><strong>Pros:</strong></p><ol><li>You can use previews and live previews for rapid UI development.</li><li>SwiftUI makes it easier for designers and web developers to work with you.</li><li>You will write less code to achieve the desired result.</li><li>WidgetKit extensions require SwiftUI and you may need to use it anyway.</li><li>It’s an opportunity to learn a valuable skill and the toolkit of the future.</li><li>In the future, it’s easier to find developers that can work with SwiftUI.</li></ol><p>This article will show you why the decision is not that easy and provide a solution that may help you if you still can’t decide between SwiftUI and UIKit.</p><h3>Cons (Why You Shouldn’t Use SwiftUI)</h3><p>Let’s start with the negative things, things that argue against the adoption of SwiftUI in your next project.</p><h4>Users on older operating systems can’t use your app</h4><p>According to this unofficial data by <a href="https://mixpanel.com/trends/#report/ios_14">Mixpanel</a>, already 93.08% of users run iOS 13 or higher (last checked: 28th November 2020). That means SwiftUI can already be used by over 90% of your potential users.</p><p>That’s a large number, and pretty common for Apple’s mobile devices. It’s also the reason why we developers feel pretty comfortable to support only the two latest iOS versions in our apps.</p><p>However, you may have other requirements. If your next or current project needs to run on older devices or support an operating system version of iOS 12 and lower, you can’t use SwiftUI.</p><h4>Problems will be harder to solve as no one faced them before</h4><p>Let’s face it, more often than we like, we have to find a solution for our current problem by searching the internet. <a href="https://stackoverflow.com/">Stack Overflow</a> is a common source for results.</p><p>While I want to caution you to not blindly copy and paste a potential solution, it is still great to know that there is nearly no problem that no one else has faced before.</p><p>However, that’s only the truth for UIKit. SwiftUI is only two years out and not widely used by companies in production. Therein lies the danger, that you will be the first one who struggles with the problem at hand.</p><p>I’ve created a small SwiftUI iPad app and had to work through three or four of those issues that took me a few weeks overall. Make sure that you realize that this could happen to you, too.</p><h4>There are some features that are only available in UIKit so far</h4><p>The last welcome additions to SwiftUI in iOS 14 include lazy stacks, a grid (like UIKit’s CollectionView), along with many other features like adding a video player or map to your SwiftUI view.</p><p>However, there are still missing pieces to make SwiftUI able to completely replace UIKit’s ViewControllers in your apps. There is no support for <a href="https://webkit.org/">WebKit</a> or for adding a text field to an alert.</p><p>You should consider this and realize that your app may not be able to be 100% SwiftUI. But more on that later.</p><h4>It will take more time because you are not that familiar with the toolkit</h4><p>It probably took you some time to become a pro in UIKit, and it will take some time in SwiftUI as well.</p><p>SwiftUI is very easy to get started with. However, you may have years of knowledge in UIKit, and this includes common bugs and gotchas, how to use the controls, delegates, testing, and shortcuts.</p><p>You won’t move at as fast a pace as what you are used to.</p><h4>Other developers in your team may not know SwiftUI</h4><p>That’s one of the biggest issues. You may think of an older developer who has stopped learning much and doesn’t like to try out new things.</p><p>I know companies where the lead developers told their interns that they can’t use Swift because it won’t be successful and Objective-C will still be the most-used iOS programming language in ten years. They were also not allowed to use ARC (automatic reference counting) because this wouldn’t be “real” programming anymore.</p><p>I’m not talking about this kind of silly developers. Your colleagues may just not have the time and are stuck in UIKit projects. As soon as you leave (vacation, sickness, or quitting your job) the other developers will have a harder time working on your code. That’s a questionable way of making yourself more valuable for your company. You should definitely consider your current team composition and discuss this point with your teammates.</p><p>Think also about future developers that will join your company. If you are certain that they will be checked for SwiftUI knowledge, this is not a showstopper. However, if that is not the case, think twice before hopping on to the SwiftUI train.</p><h4>Best practices are not yet formed</h4><p>You may only work on small applications where best practices tend to be ignored. But if you want to increase your value as a developer, you should adopt common patterns that are used by big companies to build large and scalable applications.</p><p>In UIKit, we already have many great architectures and we know how to structure our code. <a href="https://github.com/ReactiveX/RxSwift">RxSwift</a> is state-of-the-art, and we know how to do the bindings with it. Maybe you have already heard of stuff like MVVM, coordinator-pattern, and design patterns, and how they are used for iOS projects.</p><p>Your knowledge isn’t lost and many things can still be applied in SwiftUI. However, especially in combination with the <a href="https://developer.apple.com/documentation/combine">Combine</a> framework, you have to rethink how to properly write and structure your code in order to write good SwiftUI iOS applications.</p><p>Many of those best practices for programmatic navigation and other common problems are not formed yet. Therefore, you need to consider, that you may have to heavily restructure your current project in the next years as soon as your knowledge about proper solutions increases.</p><p>One thing I really miss from Apple so far is a complete guide on how we should approach testing of SwiftUI views. Especially for enterprise software, adequate code coverage is a requirement. Sadly, I haven’t seen much love for this topic from them yet.</p><h3>Pros (Why You Should Use SwiftUI)</h3><p>Okay, maybe now you are already thinking SwiftUI is not production-ready. That’s why I now want to show you why you actually should start your next project in SwiftUI.</p><h4>You can use previews and live previews for rapid UI development</h4><p>SwiftUI provides us with a beautiful preview feature to immediately see the results of our code changes to the view.</p><p>That comes in especially handy when you consider that many modifiers produce different results depending on their order.</p><p>Consider the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35e7c6d1096c5f9c523e4e3ff49e6e7c/href">https://medium.com/media/35e7c6d1096c5f9c523e4e3ff49e6e7c/href</a></iframe><p>Both Text views have the same modifiers. However, the results are completely different:</p><figure><img alt="graphic of a phone screen with the word “blue” inside a small blue rectangle and the word “red” in a large red rectangle" src="https://cdn-images-1.medium.com/max/424/1*7FRJzm96kF5-pYbIJQlzZA.png" /><figcaption>Image by me (Manuel Schulze)</figcaption></figure><p>The preview and especially the live preview, where you can even interact with buttons, etc., can really help to avoid unexpected behavior and many rebuilds for the simulator.</p><h4><strong>SwiftUI makes it easier for designers and web developers to work with you</strong></h4><p>As mentioned above, SwiftUI has a beautiful preview. The preview is not just great for us as developers, it also helps those who are not familiar with Storyboards, like designers or web developers.</p><p>You actually can create some of the UI with code but another part of it just with the powerful UI tools that <a href="https://developer.apple.com/support/xcode/">Xcode</a> provides to create SwiftUI views. You can even build complete user interfaces without the need to write a single line of code.</p><p>If you work on a team with a technical affine designer, it could make sense to show them the basics and let them create the user interfaces on their own. This reduces the coordination between the two of you and lets you focus on implementing the business logic, which will allow for faster feature deployment.</p><p>One bonus point here: I also like that the SwiftUI code and views are always in sync. With storyboards or xib-files, you always had to remember where you changed certain properties. You also couldn’t easily find changes that you’ve made in the visual tools because they never produced code that was easy to search for. With SwiftUI it doesn’t matter if you write everything in code but your colleague uses the visual tools. There is always code and its visual presentation.</p><h4><strong>You will write less code to achieve the desired result</strong></h4><p>You may have heard it already, but SwiftUI reduces the code you need to write in order to build your user interface. There were many example apps, but I like the comparison of Paul Hudson on his YouTube channel:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fqk2y-TiLDZo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dqk2y-TiLDZo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fqk2y-TiLDZo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b51e8d0cdabb0a1787e945a192a87955/href">https://medium.com/media/b51e8d0cdabb0a1787e945a192a87955/href</a></iframe><p>Note: Be careful here. Yeah, Paul was faster with SwiftUI, and you will be faster in the future as well. However, if it’s one of your first SwiftUI projects, it doesn’t make much sense to compare yourself to a person who has already written a good amount of SwiftUI tutorials and books over the last two years.</p><p>They say the best code is the one you never write. Therefore, it’s great to see how much the lines of code (LOC) can be reduced just in a small app. That’s really something I like a lot.</p><h4><strong>WidgetKit extensions require SwiftUI, and you may need to use it anyway</strong></h4><p><a href="https://developer.apple.com/widgets/">WidgetKit</a> extensions were introduced in iOS 14. They are really appreciated by the users, so it’s logical that many apps that you write will also provide a WidgetKit extension.</p><p>However, due to the short time that your code has in order to load and display its information, the widgets need to be lightweight. What else could be used for that task than those lean SwiftUI view structs?</p><p>Apple only allows WidgetKit extensions when they are written in SwiftUI. If you have to use SwiftUI anyway, it is maybe a good idea to use it for the whole application as well.</p><h4><strong>It’s an opportunity to learn a valuable skill and the toolkit of the future</strong></h4><p>In the future, more and more features will be added to SwiftUI. I’m certain that it will be the defacto standard to create user interfaces in Swift.</p><p>You can wait until you adopt it and go with UIKit for another five years easily. Yet, at some point in time, you will find fewer projects that use UIKit. So why don’t you learn it right away?</p><p>Now, could be a great moment to get a head start with this framework and become an expert before the others start learning it. It can be very beneficial to be an early adopter. This is definitely a great skill to have to progress in your career as an iOS development expert.</p><h4><strong>In the future, it will be easier to find developers that can work with SwiftUI</strong></h4><p>Oftentimes, we think a lot about how we can write clean code that will be a pleasure to work on a few years from now. That’s a good thing!</p><p>However, we also often forget how the business for which we work could evolve. New, younger developers will join our team. I often meet new developers who never learned Objective-C.</p><p>Imagine I still write every single project with Objective-C, Then I leave the company as my contract ends, and the company hires a new developer who only knows Swift. They will have a hard time maintaining my code.</p><p>That’s not exclusively a problem for contractors like myself. Your company will hire other developers, and you don’t want to give them three-week UIKit training just because you decided against SwiftUI a few years back.</p><p>Do yourself and your future colleagues a favor by using SwiftUI as soon as possible.</p><h3>The Hybrid Approach</h3><p>Both sides, pros and cons, have valid points. Even if there are no dealbreakers against SwiftUI (like support for iOS 12 and below), you may still struggle to decide what to do in your next project. That’s why I want to help you make a decision.</p><p>If you can’t decide, use both.</p><p>Apple did a fantastic job by allowing us to use a SwiftUI view inside of UIKit and start a UIViewController from SwiftUI. For my next project, I will try to start with SwiftUI to keep my code modern and lean. If I reach a point where I can’t find a solution in SwiftUI, and if UIKit provides support for the feature without using third-party code, I will switch.</p><p>It’s worth giving “SwiftUI first” a try — just make sure that you know the consequences.</p><p>If you are still anxious about starting the new project in SwiftUI, it’s a good idea to slowly transition. Start with what you are familiar with in a plain old UIKit project and use SwiftUI views here and there while getting used to the new way of building UIs in iOS.</p><p>Note: A WidgetKit extension is always a good place to start SwiftUI.</p><h3>Conclusion</h3><p>SwiftUI is a great tool to write user interfaces for all Apple devices. It’s great to see many designers and developers with different backgrounds joining the community.</p><p>However, for some of you, it will still be too early to adopt SwiftUI for the next project. That’s okay, we have side projects where we can play, and WidgetKit extensions provide us with a great place to start with SwiftUI.</p><p>If you struggle to decide between UIKit and SwiftUI, try to use a combination: either “SwiftUI first” or a conservative UIKit project with some SwiftUI views here and there.</p><p>With that, thanks for your time, and have fun with SwiftUI!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69ace40a1b46" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/swiftui-in-production-6-pros-and-cons-you-need-to-consider-69ace40a1b46">SwiftUI in Production? 6 Pros and Cons You Need to Consider</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[The Ultimate Guide to Swift Conditionals]]></title>
            <link>https://medium.com/swlh/the-ultimate-guide-to-swift-conditionals-297f17fd5c1f?source=rss-3c34554675f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/297f17fd5c1f</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift-basics]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Manuel Djirlic]]></dc:creator>
            <pubDate>Sat, 21 Nov 2020 00:03:24 GMT</pubDate>
            <atom:updated>2020-11-30T07:55:43.598Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tDlx6j-So3RQmvER" /><figcaption>Photo by <a href="https://unsplash.com/@gcalebjones?utm_source=medium&amp;utm_medium=referral">Caleb Jones</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Swift is a beautiful language that was carefully designed and has greatly evolved since it was announced back in 2014. When you compare Swift to more traditional programming languages you can easily find elements they have in common but they are done in a specific way. A more Swifty-way.</p><p>Today, I want to cover one of those basic topics, that is well-known from other programming languages, but still has its own, unique implementation in Swift. Let’s get started with conditionals in Swift.</p><h4>The if-statement</h4><p>That’s an all-time classic when it comes to programming. <strong>If</strong> a condition is true, then the code in the block of the if-statement will run.</p><pre><strong>var</strong> appleCount = 3<br><strong>var</strong> bananaCount = 1</pre><pre><strong>if</strong> appleCount &gt; bananaCount {<br>  print(&quot;We have more apples than bananas!&quot;)<br>}</pre><p>In the example above, the appleCount is higher than the bananaCount, therefore, the code gets executed and prints the statement.</p><p>Here we have already the first special flavour of Swift. We don’t need braces. They are completely optional. From my experience, I can tell you that indeed most iOS developers, including myself, omit the braces.</p><p>But it’s not just that! Swift always requires you to have a boolean expression. The Swift compiler won’t make an implicit comparison. Let me give you an example:</p><pre><strong>if</strong> appleCount {<br>  print(&quot;We have apples &gt; or &lt; 0&quot;) // This code won&#39;t work!<br>}</pre><p>In other programming languages like JavaScript, this code would be valid(with braces) and the print statement would execute. JavaScript would only check if it is a ‘truthy’ value. Other languages, would convert this implicitly to the comparisonappleCount != 0. But Swift is different in that regard.</p><blockquote>Swift always wants you to be very thoughtful.</blockquote><p>That’s why Swift doesn’t want to implicitally assume what you meant there. You could easily misinterpret what would happen when the value is negative or 0. That’s why you will get the following error message:</p><figure><img alt="The error says ‘Type ‘Int’ cannot be used as a boolean; test for ‘!=0’ instead" src="https://cdn-images-1.medium.com/max/1024/1*1-ui61DmCaDUd5gCeQG5iw.png" /></figure><p>Swift gives you a recommendation and a hint about what the compiler assumed you actually wanted to do. But it won’t do it for you. Again that’s a more robust way of programming where the language forces you to think about what you do and that’s how errors get avoided.</p><h4>else and else if</h4><p>The if-statment is often accompanied by the else- and else-if-statements. Here in code:</p><pre><strong>if</strong> appleCount &gt; bananaCount {<br>  print(&quot;We have more apples than bananas!&quot;)<br>} <strong>else</strong> <strong>if</strong> appleCount == bananaCount {<br>  print(&quot;We have the same amount of apple and bananas!&quot;)<br>} <strong>else</strong> {<br>  print(&quot;We have more bananas than apples!&quot;)<br>}</pre><p>Let’s read it line-by-line. If the appleCount variable is bigger than the bananaCount variable, execute the first print statement. <strong>Only if that’s not the case</strong> check the else-if-statement. If that’s true, execute the second print statement. Lastly, in the case that no if or else-if condition was met, print the string ‘We have more bananas than apples!’.</p><p><strong>There are four key takeaways here:</strong></p><ol><li>You need no braces for else-if as well.</li><li>An else-statement has no condition. It will always execute when none of the above if/else-if conditions were evaluated to true.</li><li>You can have only one if- and one else-condition. But you can have an unlimited amount of else-if-statements.</li><li>As soon as one condition evaluated to true, the following else-if-statements will not be evaluated! The code in their blocks will not be executed! Even if that condition would have been true as well! So be careful when multiple if-/else-if-statements could be true at the same time. Make sure that you have the correct order in place!</li></ol><h4>The if-let-statement</h4><p>Here comes the first conditional that’s only available in Swift (as far as I know). The if-let-statement is used in order to unwrap an optional.</p><p>If that left you with more questions than answers, let me very briefly explain what an optional is.</p><blockquote>An optional is a special type of a variable, constant or property that either has a value of its type or no value (nil).</blockquote><p>In my opinion, an example is more helpful here:</p><pre><strong>var</strong> optionalText: String? = &quot;Hi folks!&quot;<br>optionalText = <strong>nil</strong></pre><p>You define an optional by adding a ? after the type definition. That means that the variable optionalText can either hold a value of type String or no value (nil).</p><p>Optionals are a centerpiece of the Swift programming language and I could write a whole new blog post about them. In the context of conditionals, you only have to know, that at runtime they need to be checked if the optional has a value or not. So Swift will make sure at compile-time, that all optionals are not accessed without unwrapping them.</p><p>Okay, back to the if-let-statement.</p><p>Again, Swift wants you to be very <strong>thoughtful</strong> about what you are doing. Therefore, it doesn’t let you access a value without unwrapping it in any way. Unwrapping means, you make sure that the optional really has a value and is not nil (that could cause your programs to crash).</p><p>And here comes if-let to the rescue. Let’s continue with the example of the optional above:</p><pre><strong>var</strong> optionalText: String? = &quot;Hi folks!&quot;<br>optionalText = <strong>nil</strong></pre><pre><strong>if</strong> <strong>let</strong> text = optionalText {<br>  print(&quot;Hooray! We have a text: \(text)&quot;)<br>}</pre><p>What would happen here? The print statement doesn’t get executed. We check if the value of optionalText is not nil and if that’s the case, we’d assign the value to the constant text. However, above we set the value to nil, so nothing gets printed out.</p><pre><strong>var</strong> optionalText: String? = <strong>nil</strong><br>optionalText = &quot;Hi folks!&quot;</pre><pre><strong>if</strong> <strong>let</strong> text = optionalText {<br>  print(&quot;Hooray! We have a text: \(text)&quot;)<br>}</pre><p>In the second example, we’ve switched the assignments of nil and &quot;Hi folks! and therefore, the text gets printed to the screen. This kind of unwrapping an optional is called optional binding.</p><blockquote>Note: Have you noticed that we haven’t accessed the variable optionalText in the if-let-statement? Instead we use the constant text that we’ve used to unwrap it. We could (if we are fine with having warnings in our project) use the optional directly as well. But that’s only the case because we use string interpolation. String interpolation will transform the text to ‘nil’ or &#39;Optional(…)’ where ‘…’ would be the textual description of the value. In all other cases you need some form of unwrapping.</blockquote><h4>The guard-statement</h4><p>The guard-statement is another great Swift tool that was added in the language version 2.0. It’s often overlooked by beginners but I tend to prefer it over if-statements whenever possible (more on that later).</p><p>The guard acts like a bouncer in front of a famous club. If you’re able to fulfill his high expectations, you are allowed to get in and do your thing. But if his criteria aren’t met, he will send you back home where you were coming from.</p><p>Let me show it in code:</p><pre><strong>func</strong> danceInTheClub() {<br>  <strong>let</strong> goodShoes = <strong>true<br>  let</strong> niceHair = <strong>true<br>  let</strong> tieToMatchTheShirt = <strong>false</strong></pre><pre><strong>  guard</strong> goodShoes &amp;&amp; niceHair &amp;&amp; tieToMatchTheShirt <strong>else</strong> {<br>    <strong>return<br>  </strong>}<br>  <br>  print(&quot;Yeah, I can dance all night!&quot;)<br>}</pre><p>If we call the functiondanceInTheClub() the print statement won’t get executed. We have no tie that matches our shirt and therefore, the guard, won’t let us proceed. He simply returns from the function.</p><p>Here are a few key takeaways from guard-statements:</p><ol><li>The guard-statement only executes its else-block, when the criteria is not met!</li><li>The guard-statement uses an else at the end. This is mandatory to form a valid guard and is what happens on exit!</li><li>The code inside the guard-statement must (!!!) exit its scope. So you need one of the following: return, continue, break, or throw.</li><li>The code after the guard gets only executed if all guard conditions were evaluated to true.</li></ol><blockquote>Note: You can combine multiple conditions in one guard/if/etc. by using the &amp;&amp;- or logical AND-operator. It starts from left to right and checks one after the other. Only if all evaluate to true, the whole expression will evaluate as true. If you need only one of multiple conditions to be true, then use the || or logical OR-operator.</blockquote><h4>The guard-let-statement</h4><p>Now, you probably already have a solid enough foundation to figure out what that statement does. It’s a combination of the guard- and the if-let-statement.</p><p>It also lets you unwrap an optional by creating an optional binding and only runs the code after the guard if the optional had a value, otherwise, it will exit the scope.</p><p>Back to code:</p><pre><strong>func</strong> printNames() {<br>  <strong>let</strong> firstName = &quot;Manuel&quot;<br>  <strong>let</strong> lastName = &quot;Schulze&quot;<br>  <strong>let</strong> middleName: String? = <strong>nil</strong></pre><pre>  print(&quot;My first name is: \(firstName)&quot;)<br>  print(&quot;My last name is: \(lastName)&quot;)</pre><pre><strong>  guard</strong> <strong>let</strong> midName = middleName <strong>else</strong> {<br>    <strong>return<br>  </strong>}</pre><pre>  print(&quot;My middle name is: \(midName)&quot;)<br>}</pre><p>The guard-let-statement above will not allow us to print the middle name as I don’t have one. If I would have one, the optional would again be unwrapped and we could go on and run the code that follows the guard.</p><h4>Why do I prefer guard over if?</h4><p>The guard-statement solves in my opinion one concrete issue with if-statements.</p><p>As always, I provide you with some code. First, imagine there wouldn’t be a guard-statement in Swift:</p><pre><strong>func</strong> playAndRecordSoccer() {<br>  <strong>let</strong> haveSoccerShoes = <strong>true<br>  let</strong> haveBall = <strong>true<br>  let</strong> haveCamera = <strong>true</strong></pre><pre><strong>  if</strong> haveBall {<br>    print(&quot;We take our ball!&quot;)<br>    <strong>if</strong> haveSoccerShoes {<br>      print(&quot;We take our shoes!&quot;)<br>      <strong>if</strong> haveCamera {<br>        print(&quot;We take our camera and record our crazy goals!&quot;)<br>      }<br>    }<br>  }<br>}</pre><p>I guess you can already see, what I dislike about if-statements. You can easily end up with a very deeply nested code that gets hard to read and reason about.</p><blockquote>Note: Without the first two print statements, the code above could also be done without nesting by simply combining the conditions with the logical AND-operator (&amp;&amp;).</blockquote><p>Now let’s rewrite the function with guard-statements:</p><pre><strong>func</strong> playAndRecordSoccerGuard() {<br>  <strong>let</strong> haveSoccerShoes = <strong>true<br>  let</strong> haveBall = <strong>true<br>  let</strong> haveCamera = <strong>true</strong></pre><pre><strong>  guard</strong> haveBall <strong>else</strong> { <strong>return</strong> }<br>  print(&quot;We get our ball!&quot;)</pre><pre><strong>  guard</strong> haveSoccerShoes <strong>else</strong> { <strong>return</strong> }<br>  print(&quot;We get our shoes!&quot;)</pre><pre><strong>  guard</strong> haveCamera <strong>else</strong> { <strong>return</strong> }<br>  print(&quot;We get our camera and record our crazy goals!&quot;)<br>}</pre><p>Now we have all our code without hard to read nesting. Thanks, guard-statements!</p><blockquote>Note: I also prefer guard over if because I like to separate all the criteria into their own line if they are not highly related to each other. With if-statements, I would again need to nest them. With guards, I can have one per line and my code is still flat and readable.</blockquote><h4>Provide default-values with the nil-coalescing operator ??</h4><p>After we’ve covered two of the more complex conditional statements, let us now look at something easier to grasp.</p><p>The nil-coalescing operator (??). It is again something that is used when it comes to optionals but in this case, helps by providing default values. So if there is nil on the left side of the operator, it will use the default parameter on the right side. It gets clearer in code, so let’s dive into it:</p><pre><strong>func</strong> loadUsername() -&gt; String? {<br>  // Some code could be here that either returns a string or nil<br>  <strong>return</strong> <strong>nil<br></strong>}</pre><pre><strong>var</strong> usernameFromServer: String? = loadUsername()<br><strong>var</strong> username = usernameFromServer ?? &quot;stranger&quot;<br>print(&quot;Hello \(username)&quot;)</pre><p>Imagine that the loadUsername() makes a request for a user object that is either set or not. It will return nil if there is no user. In our code, it always returns nil instead of a real username. Here the ??-operator comes in handy, as it will assign the value on the right (“stranger”) to the variable username when the left operand is nil.</p><p>We would print “Hello stranger” to the screen.</p><h4>The ternary-operator</h4><p>Another simple operator that can be used inline is the ternary-operator. It is supported by a wide range of programming languages and you’ve probably seen it before.</p><p>First, why is it called the ternary-operator? Because it has three operands. In the order of their appearance (from left to right), they are:</p><ol><li>The condition that should be checked.</li><li>The ‘happy-path’. So the value that is used when the condition is evaluated to true.</li><li>The ‘unhappy-path’. The value that is used when the condition is evaluated to false.</li></ol><p>As always, let’s look at an example:</p><pre><strong>let</strong> limit = 0.5<br><strong>let</strong> outOfTolerance = 0.6</pre><pre><strong>var</strong> color: UIColor = outOfTolerance &lt;= limit ? .green : .red</pre><p>Let’s assume, that we are working on an app for measurements and there is a tolerance limit (limit) of 0.5. If our actual measurement (outOfTolerance) is less or equal than the limit, we display the value as text with a font color of green. If it’s higher than the limit, we want to display it in red. The code above would do just that and in this case (we are 0.6 out of tolerance) the variable color would be red.</p><blockquote>Note: You may think that there are four operands in the expression above. But here it helps to use braces to illustrate what the operands are:</blockquote><blockquote>var color: UIColor = <strong>(outOfTolerance &lt;= limit)</strong> ? .green : .red</blockquote><blockquote>The first operand is on the left of the ?, that’s the logical expression that gets evaluated. After the ? comes the second operand, the value that gets used when the condition gets evaluated to true. Finally, after the : we have the third operand that is the value that gets used when the condition evaluates to false.</blockquote><h4>The switch-statement</h4><p>The switch-statement is again an all-time classic when it comes to structured programming. But it also has special flavors in Swift, so let’s talk about it in more detail.</p><p>A switch-statement checks for equality. Let’s look at a code example and talk about it afterward.</p><pre><strong>let</strong> favoriteFruitManuel = &quot;Bananas&quot;<br><strong>let</strong> yourFavoriteFruit = &quot;Watermelons&quot;</pre><pre><strong>switch</strong> yourFavoriteFruit {<br><strong>case</strong> favoriteFruitManuel:<br>  print(&quot;BANANA!&quot;)<br><strong>case</strong> &quot;Apples&quot;:<br>  print(&quot;An apple a day, keep the doctor away!&quot;)<br><strong>default</strong>:<br>  print(&quot;You have a unique taste and like something else!&quot;)<br>}</pre><p>Let’s go through it:</p><ul><li>A switch statement can have a boolean expression but usually is used to check for equality. In the example, you can see that we check if yourFavoriteFruit is equal to favoriteFruitManuel or the string &quot;Apples”.</li><li>That means you can compare them to constants, variables, or properties.</li><li>But also check for matches with literals (42, “Hello”, true, 3.14159, etc.).</li><li>The case-statements have no indentation. They are usually on the same level as the switch statement. The block of code that gets executed if one case evaluates to true doesn&#39;t have braces but is indented.</li><li>You need to provide one case-statement for each case that could occur.</li><li>However, if that’s an unlimited amount of cases or you just don’t want/have to provide a case-statement for each case, you can use the default-case, which works like the else-statement in if-else. More on the default-case later.</li><li>Unlike many other languages, you don’t need a break at the end of the case to avoid that your program calls every single case that follows (falls through).</li></ul><blockquote>Note: The last one sounds pretty absurd. But that’s actually how many programming languages handle switch-statements and a common source of errors. In these programming languages as soon as you have one match, all code in the following case-statements gets executed until a break was found. You can easily forget one and wonder why two cases are executed at the same time. But don’t care, Swift got your back!</blockquote><blockquote>However, if you want that behavior you need to tell that Swift explicitly by using the fallthrough keyword. It will fall through to the following case.</blockquote><p>You also don’t have to duplicate code if several cases-blocks look the same. You can just separate them with a ,.</p><pre><strong>enum</strong> Days {<br>  <strong>case</strong> monday, tuesday, wednesday, thursday, friday<br>  <strong>case</strong> saturday, sunday<br>}</pre><pre><strong>let</strong> today = Days.saturday</pre><pre><strong>switch</strong> today {<br><strong>case</strong> .saturday, .sunday:<br>  print(&quot;Hooray weekend!&quot;)<br><strong>default</strong>:<br>  print(&quot;Yeah, coding time!&quot;)<br>}</pre><p>Here we have two interesting things.</p><ol><li>You can see, how we separate multiple values in a case-statement with case .saturday, .sunday:. They share the code that gets executed when there is a match of today with one of them.</li><li>Notice, that this is where switch-statements really shine. They are perfect in conjunction with enums. For an enum, you provide a fixed amount of cases (don’t confuse them with switch-cases) that can occur. Like days in a week.</li></ol><blockquote>Note: Why a switch-statement works so great with enums? Imagine, you have a fixed amount of cases, for example, errors that can occur. Now you handle all of them specifically in your switch-statement (no default-case). Suddenly, your project manager approaches you to add another error case that should be handled as well. You add it to your enum and your project doesn&#39;t compile anymore!</blockquote><blockquote>Great!</blockquote><blockquote>No really, now you see where the specific handling is missing and you can act upon that information and write your custom code for that error. With if-statements, you wouldn’t get any information that there is one case missing. You would need to remember all places where the changes are now needed.</blockquote><h4>Switch-statements: Optionals</h4><p>So we looked at if and if-let. We’ve also seen guard and guard-let. Well, we have no switch and switch-let but case and case-let.</p><p>It works the same as the other conditionals. Case-let-statements create an optional binding and if the optional has a value it will be unwrapped and the case block gets executed. However, mostly you will see it combined with a where-clause.</p><p>Let me give you an example of that:</p><pre><strong>let</strong> favoriteBook: String? = &quot;Clean Coder&quot;</pre><pre><strong>switch</strong> favoriteBook {<br><strong>case</strong> <strong>let</strong> book <strong>where</strong> book == &quot;Clean Coder&quot;:<br>  print(&quot;A great book that teaches professionalism as a coder&quot;)<br><strong>case</strong> <strong>let</strong> book <strong>where</strong> book == &quot;Refactoring&quot;:<br>  print(&quot;A great book that teaches you how to improve your code&quot;)<br><strong>default</strong>:<br>  print(&quot;Another favorite book or none&quot;)<br>}</pre><p>You make two things at once here. First, you unwrap the optional or create an optional binding. If the constant favoriteBook has a value and that value is “Clean Coder” it will match the first case. For a value of “Refactoring” it will match the second. In all other cases (another String or nil) it will print “Another favorite book or none”.</p><p>That’s already pretty handy, but I’m not the biggest fan of the where-clause. So we can use a different approach. For that, you need to know, that an optional is under the hood just an enum. It has two cases, that look roughly like this:some(value) and none.</p><p>With that we can write some really neat code:</p><pre><strong>let</strong> cleanCoder = &quot;Clean Coder&quot;<br><strong>let</strong> refactoring = &quot;Refactoring&quot;<br><strong>let</strong> favoriteBook: String? = <strong>nil</strong></pre><pre><strong>switch</strong> favoriteBook {<br><strong>case</strong> .some(cleanCoder):<br>  print(&quot;\(cleanCoder): Professionalism as a coder&quot;)<br><strong>case</strong> .some(refactoring):<br>  print(&quot;\(refactoring): How to improve your code&quot;)<br><strong>case</strong> .some(<strong>let</strong> val):<br>  print(&quot;You love another book: \(val)&quot;)<br><strong>default</strong>:<br>  print(&quot;You have no favorite book.&quot;)<br>}</pre><p>For me, that is a lot more readable and we can even check if a value is set at all.</p><h4>Switch-statements: Check for ranges</h4><p>You are not only able to check for exact matches, but you can also check for ranges.</p><p>Code speaks more than a thousand words, here we go:</p><pre><strong>let</strong> monthOfBirth = 11</pre><pre><strong>switch</strong> monthOfBirth {<br><strong>case</strong> ..&lt;7:<br>  print(&quot;You are born in the first half of the year&quot;)<br><strong>case</strong> 7...12:<br>  print(&quot;You are born in the second half of the year&quot;)<br><strong>default</strong>:<br>  print(&quot;That&#39;s not a valid month!&quot;)<br>}</pre><p>I won’t cover now how these ranges work in detail, this is part of another story. But here are the key takeaways:</p><ol><li>We check for a range that is less than 7 (July) with ..&lt;7.</li><li>Then we check if the in the second case if the value is between 7 and 12 by using 7…12.</li><li>Lastly, we cover the default case. It’s not enough that we know, that these values will never be above 12. The Swift compiler doesn’t know that. He only sees an integer and that means it could be a much bigger range than 1–12. The switch wouldn’t be exhaustive, that’s why we need a default-case.</li></ol><blockquote>Spot the bug: Speaking of integers, can you spot the error in the example above? In the first case, we only check if the value is below 7. Well, that means -1 would also be allowed there and not throw the default-case but instead the first case. You can avoid that by either writing 1…7 or using an unsigned integer (UInt) that can only hold positive integer values (be careful, 0 would still be possible). I would prefer the first option as it is recommended by Swift to mostly use the type Int for readability and interoperatability and we don’t have to handle the 0 case specifically.</blockquote><h4>Switch-statements: Do I need a default-case?</h4><p>The last point that I want to discuss is when do you need a default-case?</p><p>It’s actually quite easy. When you provide all possible options, you don’t need one. The switch-statement is exhaustive and knows how to handle each situation. Frequently, you will find yourself not being able to provide all cases (e.g. when checking for values of type String or numbers). Then you will need a default-case.</p><p>Additionally, when you don’t need to specify handling for all cases (even if there are just 2 or 3), it’s completely fine to write just the cases explicitly that you need and catch all other occurrences with the default-case.</p><p>A final code example:</p><pre><strong>let</strong> isRaining = <strong>false</strong></pre><pre><strong>switch</strong> isRaining {<br><strong>case</strong> <strong>true</strong>:<br>  print(&quot;Get my umbrella!&quot;)<br><strong>case</strong> <strong>false</strong>:<br>  print(&quot;Get my sunglasses&quot;)<br>}</pre><pre><strong>let</strong> yourAnswerToTheMeaningOfLife = 42</pre><pre><strong>switch</strong> yourAnswerToTheMeaningOfLife {<br><strong>case</strong> 42:<br>  print(&quot;That&#39;s true 42 is the answer to the question of life&quot;)<br><strong>default</strong>:<br>  print(&quot;No that&#39;s wrong! It&#39;s 42!&quot;)<br>}</pre><p>In the first switch-statement, we provide all possible values for equality checks in the case-statements. The constant isRaining can only be true or false. Therefore, we don’t need the default case.</p><p>In the second switch-statement, there is no way to provide all values (at least if you don’t want to type more than 4 billion cases). So we just handle our specific case (42) and let the others fall through to the default case.</p><p><strong>What would happen if we omit the default-case in the last switch-statement?</strong></p><p>We would get an error by Swift:</p><figure><img alt="The error says: ‘Swift must be exhaustive`." src="https://cdn-images-1.medium.com/max/741/1*vw7p8fimRgpMspWYjMQ7Cg.png" /></figure><h4>Summary</h4><p>We’ve covered a lot of different conditionals today that should be part of your tool belt while becoming an expert in Swift.</p><p>There are different scenarios when you want to use them. Therefore, let me give you a brief overview of all of them:</p><ol><li><strong>If-statements run the code in their block when their condition evaluates to true. They can have an additional else-if-statement that checks if another condition is true and runs its code if that&#39;s the case. If none of the if- and else-if-statements evaluated to true, the optional else case would run.</strong></li><li><strong>The if-let-statement works like an if-statement but creates an optional binding. If the optional has a value, the code of the if-let will run and the value is unwrapped in the conditional binding constant.</strong></li><li><strong>The guard-statement acts like a bouncer. It will only let you continue to run the code in the scope if the condition evaluates to true. It has always an else-case in which the code must exit (with </strong><strong>return, </strong><strong>continue, </strong><strong>break, or </strong><strong>throw).</strong></li><li><strong>The guard-let-statement also creates an optional binding. If the optional has a value, it will skip the guard’s else and run the code that follows. You can use the constant of the optional binding to have the value unwrapped until you reach the end of the scope.</strong></li><li><strong>The </strong><strong>??-operator allows you to provide default values, for the case that the operand on the left is </strong><strong>nil.</strong></li><li><strong>The ternary operator lets you inline a conditional assignment where you want to use one of two values.</strong></li><li><strong>The switch statement lets you check for equality of the expression/value with different cases. You don’t need a </strong><strong>break in the cases to avoid a falling through in Swift. Swift will always only run the code in the case that was matched. You can (and oftentimes have to) provide a default case, that will execute some code when no case was evaluated to true.</strong></li></ol><p>That’s it for today. Are there any more tips and tricks about conditionals that I haven’t covered, but you love to use? Have I even forgotten a conditional? Let me know in the comments! Can’t wait to hear from you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=297f17fd5c1f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/the-ultimate-guide-to-swift-conditionals-297f17fd5c1f">The Ultimate Guide to Swift Conditionals</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[6 essential skills for insanely ambitious developers besides coding]]></title>
            <link>https://manuel-schulze.medium.com/6-essential-skills-for-insanely-ambitious-developers-besides-coding-28cde5c42941?source=rss-3c34554675f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/28cde5c42941</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Manuel Djirlic]]></dc:creator>
            <pubDate>Sat, 14 Nov 2020 11:07:48 GMT</pubDate>
            <atom:updated>2020-11-15T09:22:30.586Z</atom:updated>
            <content:encoded><![CDATA[<h3>6 Essential Skills for Ambitious Developers Besides Coding</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4T28AE91OpkASkYc" /><figcaption>Photo by <a href="https://unsplash.com/@svi_designs?utm_source=medium&amp;utm_medium=referral">Sergi Viladesau</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Becoming a good software developer is hard.</p><p>It takes years of dedicated learning to really get a grasp on all the paradigms that you need to know about. You have to dive deep into your programming language to fully understand how certain features work and get ahead of the game. In addition to that, there are design patterns, tools, algorithms, etc., that we should have working experience with.</p><p><strong>Really, it is hard to become an expert in software development.</strong></p><p>Even worse, it’s not like you are done after the initial learning phase. We are in a fast-paced environment where new tools, paradigms, programming languages, and fancy libraries come up every month or so.</p><p>With all that to learn and master, <strong>we often forget to realize that ultimately we work with people</strong>. And in order to work with people, you need to master a completely different skillset.</p><p>Those abilities may not necessarily improve the quality of your code. However, they will have a tremendous impact on your career and be beneficial in every single project you work in.</p><p>I wouldn&#39;t say these skills are more important than your technical knowledge. But in order to become a true professional and an expert in your field, it takes more than a solid coding background.</p><p>Today, I want to give you a set of the most important abilities (at least in my opinion) besides coding.</p><h4>The art of communication</h4><p>I know, stereotypically we tend to be nerdy and sit in front of our desks the whole day. Others neither hear nor see us and we are the magicians that just get insanely complex stuff done.</p><p>However, it is important that you learn how to communicate with others. I’m not saying you have to change the core of your being. If you are an introvert (and I am, too) that’s more than okay and probably made you the developer you are today. But you should be able to communicate effectively, efficiently (don’t overdo this!), virtual as well as in-person.</p><p>Becoming good at communicating with your team, boss, clients, and other members of your organization is not just crucial for the next step in the career ladder. It is also important to connect with them. How can they trust in you, if they don’t know you and vice-versa? How can you work efficiently when you don’t have trust in your team and vice-versa?</p><p>Again, it doesn’t take much here, but I give you a list of a few things that you should be able to do through communication:</p><p><strong>Small-talk</strong></p><p>I got it, many people don’t like to speak just for the sake of starting a 5-minute talk that barely scratches the surface. However, it doesn’t hurt asking a colleague that you meet in the kitchen how they are or what they’ve spent their weekend on. On the contrary, it can have a huge impact and make others like you which is never a bad thing.</p><p><strong>Saying no</strong></p><p>Okay, that sounds pretty negative, doesn’t it? But it is incredibly important to learn this one skill!</p><p>You don’t want to do other people&#39;s jobs just because you never learned how to draw boundaries.</p><p>You can’t finish a feature in-time? Then you have to tell your project manager/product owner. They will try to negotiate with you if you can make it work somehow. But you know you can’t. Don’t try, that’s really unprofessional. They can only take action and change plans if you make clear that it won’t be finished as they’ve planned.</p><blockquote>Never say I’ll try!</blockquote><p><strong>Note:</strong> Sure, you should always give your best and try to make it work. But don’t give commitments where you don’t completely believe in.</p><p><strong>Communication with non-tech people</strong></p><p>We work a lot with other developers. They often share the same interests with us and it is really easy to talk to them just because they are like-minded. Nevertheless, on a daily basis, we work with designers, project managers, product owners, scrum masters, clients, etc. You need to communicate with them as well, so you should definitely strengthen this skill.</p><p>If you try to explain something to a non-tech person and you see an idle glance in their big eyes, you know you have to improve in this area.</p><p><strong>Bonus tip</strong></p><p>Never talk bad about others behind their back. It doesn&#39;t matter if they really messed up. You don’t know why they did something in that way and humans do mistakes all the time. Remember, even if you are a top-notch programmer, you are also a human being and you will fail. So if they did something wrong, talk with them about it (avoid blaming) and try to help.</p><h4>Seeing the bigger picture</h4><p>The next two points really belong to each other, but let’s start with seeing the bigger picture. This is a wish of project managers, I’ve consistently heard in most of my projects as a contractor. Developers (including myself) don’t see what they are programming for.</p><p>I know in our day-to-day work we have to handle complex problems. We also try to do things according to the best practices and it’s easy to just lose sight of the business case, our clients, and the setting in which we operate.</p><p>Maybe there is another team that later needs to maintain the code, so it may not be the best idea to use the ‘new kid on the block’ tool to create the application. The other developers potentially don’t know it and have a harder time doing their job.</p><p>Your implemented error notifications are really great for you as a developer but are they also that great for your customer base which doesn’t have a technical background?</p><p>Always remember, who your users are and what their level of expertise is. Think about, what role does this feature play in the business context and for your company. Never get lost in the daily chaos and lose the long-term goals and intentions out of sight.</p><p><strong>Bonus tip:</strong> You can much easier prioritize and make better decisions when you keep the bigger picture in your mind. That helps also to improve your code as the best code is the one you don’t need to write.</p><h4>Gain domain expertise</h4><p>Let me tell you a story. I worked for a subsidiary of a big German car manufacturer. I was just starting as a working student and had a talk with some of my junior dev colleagues. I asked them if they specifically tried to gain knowledge in the car industry. They said, that they are more focused on the programming industry and they told me of a guy working for the company who knew nearly every detail about every car the company produced and he was pretty familiar with how the different parts of a car work together. He told them:</p><blockquote>“How can you work for this company when you don’t know the products or how they work?!?”</blockquote><p>We had a laugh. Oh lord, were we naïve!</p><p>He was completely right and he was behaving like a professional while we were amateurs.</p><p><strong>Yes, you are a software developer but ultimately you are a problem solver</strong>.</p><p>How can you solve problems when you don’t know what they are about? How can you detect falsy requirements for a story when you have no clue about the domain you’re working in?</p><p>You can’t.</p><p>You don’t have to become the most knowledgeable person in this field. After all, you have to maintain your rock-solid technical knowledge. But you should be able to talk easily about the industry and the context in which your company is operating, and find errors in requirements most of the time.</p><p>You can easily get started by reading a book or two about your industry. Try to read articles about it quite regularly. Additionally, speak to domain experts during lunch at least once a month.</p><p>Believe me, this is a highly underrated skill that can really make the difference between a good and a great developer. It also helps in seeing the bigger picture which we already looked at.</p><h4>Negotiation</h4><p>Okay, that one seems obvious. You need to be able to negotiate to earn more money. Well, that is true, but not the end of the story.</p><p>You try to make deals almost every day. During your sprint planning, you have to discuss how many story points a user story gets estimated to. How about deadlines and what features you can provide up to this point? Again there is negotiation needed. Other important things are architectures, design patterns, or guidelines you and your team have to agree on.</p><p>For all of these situations, you need negotiation.</p><p>Let me examine one case more thoroughly. I already told you, that you have to learn to say no.</p><p>I still think that this is one of the most important skills. But even more important afterward is to find ways to say yes.</p><p>You maybe cannot commit to delivering the full user interface for the iOS application until the end of the week. But maybe you can find a way to make it work. Here is an example of you talking to your project manager (Tom in this case):</p><blockquote><strong>Tom:</strong> Hi, we really need to finish the whole user interface and fill it with dummy data until Friday!<br><strong>You:</strong> Hi Tom, sorry that is definitely not possible. I’ve made my estimations and that will at least take two more weeks. <br><strong>Tom:</strong> That is way too long! I have a meeting with the management on Monday where I have to show how the final product will look like. This could easily get us into trouble, our budget cut, and our project canceled.<br><strong>You:</strong> Is it an option to just show the initial screen and the screens we navigate from there. We could then simply omit the detail screens and with some overtime that should be feasible.<br><strong>Tom:</strong> No, they really want to see the whole process with all the detail screens. They need something to click through to show the final product to our clients. It doesn’t have to contain nice code. It should just work for that day. We can make it in a proper way later.<br><strong>You:</strong> We don’t have the time to make it in a proper way afterward as I know our estimation for the project. But from what you‘ve been saying, I would assume that a click-dummy without self-written code would be enough.<br><strong>Tom:</strong> Well, yeah, when I can deploy that to an iPhone and show it to them by clicking through. Could you create something like that for the end of the week?<br><strong>You:</strong> Sure, I can create something for you in a day or two, and then we have even enough time to test it and you can show it to our management and our clients as well.<br><strong>Tom:</strong> Sounds great! Let’s do it! Thank you, very much!</blockquote><p>That’s exactly how you should behave in such situations. You should try to give a yes, but never commit to something or say you’ll try when you can’t assure that you will make it in time. At the end of the discussion (negotiation), both parties were happy and had the problem solved in a good way.</p><h4>Ownership</h4><p>I first discovered the topic by reading the book ‘Extreme Ownership’ by Jocko Willink and I was hooked. In a nutshell, it says, that you take full responsibility for the project, the people in there, your actions, and theirs.</p><p>Oftentimes, I’ve ended up blaming others for errors that occurred. It’s a strange tendency that most of us have to first look for flaws in others. Recently, I’ve had to write more than 80 unit tests for an application that wasn’t tested at all! A few years ago, my reaction would have been to start finger-pointing and really getting angry at the developer who created that mess.</p><p>Nowadays, I think differently. I know that he wasn’t that secure with Jasmine unit tests. I also know that he had a lot of time and in the end, I was the one who approved his pull request. It was my responsibility and, therefore, my fault that no unit tests were in place. I did my homework and wrote even an <a href="https://manuel-schulze.medium.com/pull-requests-why-you-should-never-delay-code-quality-4ef518103065">article</a> about that topic to remind myself that you never should allow sloppy code to go into production.</p><p>There are other examples, was it the fault of the junior developer that he implemented the feature in the wrong way, or did you do a bad job at helping him out and questioning his understanding. Maybe the acceptance criteria weren’t that clear written and you should have noticed as you have by far more knowledge in the area.</p><p>There is no point in searching for mistakes in others. Even if it was their fault, you gain nothing from that. But you can use it as a chance to take responsibility, grow as a developer, and try to avoid these problems in the future.</p><h4>Conclusion</h4><p>Software development is hard and it’s not just the technical part that requires our continuous improvement.</p><p>In this post, I showed you 5 areas you need to work on outside of coding. These are:</p><ul><li><strong>The art of communication</strong></li><li><strong>Seeing the bigger picture</strong></li><li><strong>Gain domain expertise</strong></li><li><strong>Negotiation</strong></li><li><strong>Ownership</strong></li></ul><p>The list is obviously not complete. There are other topics like teaching less experienced developers or self-organization to get more out of your time. However, I feel that the list above gives you a good start and sets the stage for developing a mindset that you must grow as a developer by growing as a person.</p><p>I want to end this post with a great quote:</p><blockquote>“What you get by achieving your goals is not as important as what you become by achieving your goals.”<br>- Henry David Thoreau</blockquote><h4>Further reading</h4><p>Here are my book recommendations where some of the ideas/solutions from this blog post were taken out off:</p><ul><li><a href="https://www.amazon.com/Pragmatic-Programmer-journey-mastery-Anniversary/dp/0135957052/ref=tmm_hrd_swatch_0?_encoding=UTF8&amp;qid=1605311631&amp;sr=8-1">‘The Pragmatic Programmer’ by David Thomas and Andrew Hunt.</a></li><li><a href="https://www.amazon.com/Clean-Coder-Conduct-Professional-Programmers/dp/0137081073/ref=sr_1_1?dchild=1&amp;keywords=clean+coder&amp;qid=1605311738&amp;sr=8-1">‘Clean Coder’ by Robert C. Martin.</a></li><li><a href="https://www.amazon.com/Extreme-Ownership-U-S-Navy-SEALs/dp/1250183863/ref=tmm_hrd_swatch_0?_encoding=UTF8&amp;qid=1605311803&amp;sr=8-1">‘Extreme Ownership’ by Jocko Willink and Leif Babin.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28cde5c42941" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Does Swift Type Inference Work?]]></title>
            <link>https://medium.com/swlh/how-does-swift-type-inference-work-c287fae34da0?source=rss-3c34554675f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c287fae34da0</guid>
            <category><![CDATA[swift-basics]]></category>
            <category><![CDATA[swift-5]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Manuel Djirlic]]></dc:creator>
            <pubDate>Sat, 07 Nov 2020 19:46:08 GMT</pubDate>
            <atom:updated>2020-11-16T23:53:44.213Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z1mSY8nBPDXyKH8fWxb4TQ.png" /><figcaption>Photo by Manuel Schulze</figcaption></figure><p>Swift is a statically typed programming language which means that the compiler needs to be able to figure out the type of each variable, constant, or property at compile time. However, thanks to Swift’s type inference, it is not always necessary to explicitly specify the type.</p><p>Today, I want to show you how type inference works and how it does help you to keep your code more lightweight.</p><h4>Swift — a statically typed language</h4><p>I like to have concrete examples when learning new things. So let’s compare a statically typed with a loosely typed language. Due to my experience in iOS and frontend web development, I use Swift (statically) and JavaScript (loosely).</p><p>Here you can see a completely valid function in JavaScript:</p><pre>function jsFunc() {<br>  var value = 32;<br>  value = “Hi, guys!”;<br>}</pre><p>In the function above, we simply create a variable that is initialized with a value of 32. In the next line, the same variable gets a new value of type string assigned. You could even add another line and make an array out of that variable or assign an object to it. JavaScript doesn’t care. Because of that, you lose some protection against runtime errors.</p><p>Imagine you would call console.log(value.toLowerCase()); at the end of the function above. It would print out <em>“hi, guys!”</em>. Well, that’s no surprise. Next, add the log statement before changing the value in the second line of the function and call it while the value is still 32. Now, you get the following error:</p><blockquote>Uncaught TypeError: value.toLowerString is not a function</blockquote><p>The reason is that integers don’t have the function toLowerCase<em>. </em>Again, that’s the expected behavior but it&#39;s error-prone when you use the same variable in different places and not just in the same function. You could accidentally assign a wrong value without the compiler warning you.</p><p>Now, let’s do the same in Swift:</p><pre><strong>func</strong> swiftFunc() {<br>  <strong>var</strong> value: Int = 32<br>  value = &quot;Hi, guys!&quot;<br>}</pre><p>While in JavaScript the code was valid, in Swift it isn’t and we get a compiler error:</p><blockquote>Cannot assign value of type ‘String’ to type ‘Int’</blockquote><p>The reason is that a statically typed language allows no interchanging of types. If something is an integer at the beginning, it will stay an integer for the rest of its lifetime. That avoids nasty runtime errors. Sure, if you never do mistakes when you are programming, it doesn&#39;t matter. For the rest of us, it’s a nice feature to have that catches some of our shortcomings.</p><p>With the basics out of the way, let’s now look into explicit types first, before diving into type inference in Swift.</p><h4>Explicitly typed assignments</h4><p>So Swift needs to know the type at compile time. How does it work? First, let’s look at explicitly (or manually) specifying the type.</p><pre><strong>let</strong> stringLabel: String = &quot;I am a string!&quot;<br><strong>var</strong> intValue: Int = 4</pre><p>Here we have two assignments with explicit types. We tell Swift that the constant (let) is of type String and the variable (var) is of type Int. We can’t assign a double value to the variable <em>intValue</em>. That’s true for the initial and all other assignments throughout the lifetime of the variable. A constant on the other hand can only be assigned a value once but it again has to be of the type you specified (here String).</p><h4>Implicitly typed assignments (Swift type inference)</h4><p>The process described above works fine and theoretically, you could write all your Swift code with explicit types. However, we programmers tend to keep things as short and lightweight as possible and use the great features our programming language provides. Hence, here is another example, that uses implicit types.</p><pre><strong>let</strong> stringLabel = &quot;I am a string!&quot;<br><strong>var</strong> intValue = 4</pre><p>Okay, it’s actually the same code and I just omitted the explicit types, but it does work! Swift sees the constant and the assignment and is able to <strong>infer </strong>that we assign a String value to it and therefore the constant has to be a String constant. The same is true for the variable where we assign an Int<em> </em>value.</p><p>Important for the variable example is that we again can never reassign a value to the variable <em>intValue</em> that has a type other than Int. Swift just figured out the type of the variable on its own. That doesn’t mean it changes anything regarding its strongly/statically typed nature.</p><p>Well, and that is what type inference in Swift is all about. Swift is able to detect types on its own.</p><p>But now you may ask, why we even need those explicit types when writing Swift code.</p><h4>The limits of type inference</h4><p>Even though the Swift compiler is pretty good at understanding what we want and able to infer types, it can not read our minds. Let’s say we want to create a Float value. How can you do that? You could come up with the following solution:</p><pre><strong>let</strong> floatValue = 70.0</pre><p>Sadly, Swift has Double as its default floating-point type. Therefore, the code above would create a double and not a float constant.</p><p>We can solve this issue in different ways:</p><pre><strong>let</strong> explicitFloatValue: Float = 70.0<br><strong>let</strong> castedFloatValue = Float(70.0)<br><strong>let</strong> floatValueWithAsFloat = 70.0 as Float</pre><p>You see, you need to provide Swift with more information to make it realize that you want this constant to be of type Float. You could use an explicit type, which is what I would do in most cases. Alternatively, you can use the casting operator to cast the double value into a Float or tell Swift that you want this value as a Float.</p><p>Another example would be the following code:</p><pre><strong>func</strong> testFunc() {<br>  <strong>let</strong> myValue<br>  <strong>let</strong> someCondition = true</pre><pre>  <strong>if</strong> someCondition<strong> </strong>{<br>    myValue = 2<br>  } else {<br>    myValue = 4<br>  }<br>}</pre><p>The code above doesn’t work. It’s unrelated to the fact that <em>myValue</em> is a constant. It’s just that you have only two options in Swift. You can either assign a value at the beginning so Swift can infer the type on its own or tell Swift what the type actually is.</p><p>To fix it, you could use again an explicit type:</p><pre><strong>func</strong> testFunc() {<br>  <strong>let</strong> myValue: Int<br>  <strong>let</strong> someCondition = true</pre><pre><strong>  if</strong> someCondition<strong> </strong>{<br>    myValue = 2<br>  } else {<br>    myValue = 4<br>  }<br>}</pre><p><strong>Edit:</strong> I found another case where you need to provide the type explicitly. When you work optionals (values that can be nil or of the type you’ve provided) you may need to tell Swift that the current variable/constant/property can be set to nil or if you set it to nil right away.</p><pre><strong>let</strong> optionalValue = nil // Error<br><strong>let</strong> workingOptional: String? = nil // Does work</pre><pre><strong>let</strong> nonOptional = &quot;Hello&quot; // Constant of type String<br><strong>var</strong> beCareful = nonOptional // Variable of type String (not String?)<br><strong>var</strong> better: String? = nonOptional // Variable of type String?<br>beCareful = nil // Error, Swift thinks beCarful is of type String<br>better = nil // Does work, Swift knows its either String or nil</pre><h4>Bonus tip</h4><p>Swift <strong>never</strong> converts types implicitly. That means you cannot do arithmetic operations or something similar without casting a value.</p><pre><strong>let</strong> doubleValue = 70.0<br><strong>let</strong> floatValue: Float = 30.0<br><strong>let</strong> sum = doubleValue + floatValue // This fails</pre><p>The code above wouldn’t compile and you’d get the following error:</p><blockquote>Binary operator ‘+’ cannot be applied to operands of type ‘Float’ and ‘Double’</blockquote><p>In other programming languages, this may have worked, because they implicitly convert the values. But Swift wants to help you and avoid unexpected behavior, so you have to explicitly tell Swift how the conversion should look like. Hence, to make it work, you’d need to cast one of those values to the other.</p><h4>Conclusion</h4><p>Swift’s type inference allows you to reduce the number of characters you need to write. It’s a neat tool, that you should have in mind and use to keep your code lightweight.</p><p>Thanks to it’s statically typed nature, Swift also protects us against a lot of runtime errors that could happen because we accidentally reassign values of different types than intended.</p><p>That’s it for today and as always be a professional, guys!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c287fae34da0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/how-does-swift-type-inference-work-c287fae34da0">How Does Swift Type Inference Work?</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>