<?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 Moritz Lang on Medium]]></title>
        <description><![CDATA[Stories by Moritz Lang on Medium]]></description>
        <link>https://medium.com/@slashmo?source=rss-5f7b89e840d7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*97L93k0KyRjWTCvbLlgsZQ@2x.jpeg</url>
            <title>Stories by Moritz Lang on Medium</title>
            <link>https://medium.com/@slashmo?source=rss-5f7b89e840d7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 21:20:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@slashmo/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[How to get started with iOS Development]]></title>
            <link>https://medium.com/code-university/how-to-get-started-with-ios-development-9baec87cf975?source=rss-5f7b89e840d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/9baec87cf975</guid>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Moritz Lang]]></dc:creator>
            <pubDate>Tue, 04 Sep 2018 15:44:01 GMT</pubDate>
            <atom:updated>2018-09-04T15:44:01.797Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2AN_pnRm2Xk1MQ-Zni0lbg.jpeg" /><figcaption><a href="https://www.pexels.com/photo/woman-using-laptop-1181279/">https://www.pexels.com/photo/woman-using-laptop-1181279/</a></figcaption></figure><p>So you finally did it. You decided to look into iOS Development. Enthusiastically, you want to create your first million-dollar app, but soon are overwhelmed by the sheer amount of stuff to learn and resources to learn from.</p><p>In the following few lines, I’m going to provide you with all the basics I wish I had known when I first started. Although I assume you’re a complete beginner to programming, this post can also be of help for developers coming from other areas.</p><h4>Programming language</h4><p>First things first: I recommend starting to build a solid foundation in programming. Rather than jumping right into it, copy-pasting awful code from various sources without even understanding a thing, only to notice that the next million dollar app is not a feasible thing to do as a one-man-army. Simple concepts on how to solve problems will help you a lot more. Applied to iOS-Development, this means getting to know Swift. It’s an open source programming language built by Apple to replace their much older language Objective-C. Until 2014, Objective-C was the only official way to write iOS applications. Although Objective-C is still a thing, especially in larger applications with a lot of legacy code, I assume that a few years down the road Apple will begin to start deprecating the support for it. This means, that you only, if at all, have to be able to read/understand code written in Objective-C. Therefore, starting out with with Swift is the way to go. At the bottom of this post, I’ll add some links on how to get started with the programming language.</p><h4>Development environment</h4><p>Swift, having the benefit of being open source, already has partial support to run on other platforms such as Linux with more to come in the future. iOS-Development, on the other hand, depends on multiple tools that only run on macOS, Apple’s operating system. I assume this is not going to change very soon as almost all of the tools used to build iOS apps are closed source and because Apple is making a lot of money with Mac sales. That basically leaves you with only one option: Buying a Mac. But as mentioned before, I recommend starting with learning Swift anyways, which you can do on any modern computer using tools like <a href="https://docker.com/">Docker</a> and <a href="https://github.com/microsoft/vscode">Visual Studio Code</a> to see if it’s even a thing you’re willing to invest your time and money in.</p><h4>Tools</h4><p>Speaking of tools, once you decided to pursue your dream of writing iOS apps by getting your hands on macOS, it’s time to think about the applications you are going to need to build your own. The thing you’ll spend most of the time is called <a href="https://developer.apple.com/xcode">Xcode</a>. Xcode is an IDE, which is basically a code editor with a lot more advanced features. Don’t worry too much about those in the beginning as you’ll learn about the most important ones soon enough.</p><p>The other tool you’ll have the pleasure to work with will be the Terminal. Don’t be shy to play around with it. I know working without a graphical interface can be daunting at first, but at the same time, the possibilities it opens up are endless. I’d recommend to first get into some basic commands to switch directories, copy files, etc. In my opinion, it’s also helpful to learn about <a href="https://git-scm.com/">Git</a>, a version control system, rather sooner than later, because it’s at the core of each software development project.</p><h4>What about you?</h4><p>Did you already start learning Swift or iOS-Development? What methods did you use and what did you do at the very beginning?</p><p>To wrap up this short post, here are some links to the most important things I mentioned:</p><ul><li><a href="https://swift.org/swift-book">The official Swift book</a> (also available in iBooks)</li><li><a href="https://developer.apple.com/swift/resources/">Overview of Swift &amp; Xcode learning resources</a></li><li><a href="https://try.github.io/">Learn Git</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9baec87cf975" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-university/how-to-get-started-with-ios-development-9baec87cf975">How to get started with iOS Development</a> was originally published in <a href="https://medium.com/code-university">CODE University of Applied Sciences</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optionals in Swift]]></title>
            <link>https://medium.com/slashkeys-development/the-optional-e88c2522663a?source=rss-5f7b89e840d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e88c2522663a</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[optionals]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Moritz Lang]]></dc:creator>
            <pubDate>Sun, 10 Jun 2018 14:25:11 GMT</pubDate>
            <atom:updated>2019-01-03T14:25:56.970Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4AwPR5QPsXwvCaIR3oczxg.jpeg" /></figure><h4>Behind the scenes of one of Swift’s biggest differentiators</h4><p>No matter how long your Swift journey has been so far, you definitely heard about Optionals or at least saw some ? or ! in your code. In this post, I’m going to show you what Optionals are, how they work under the hood and some best practices for dealing with them.</p><p>Although this post uses some more advanced terms like Generics, you should still be able to understand the key parts of this app if you never heard of such a thing.</p><h3>What’s a statically typed language?</h3><p>Swift is a statically typed language. This means that in order for the compiler to work successfully, every variable, constant, and function must have their <strong>type declared in advance</strong> (before the compilation).</p><pre>// No type: Compiler Error ⚠️<br>var x<br><br>// Explicitly typed integer<br>var x: Int = 0<br><br>// Implicitely typed integer<br>var y = 0</pre><p>As demonstrated in the example above, you can either explicitly specify the type, or let the compiler infer it based on its value.</p><p>Declaring a type is a <strong>one-time-thing</strong>. After declaring a variable, constant, or function, its <strong>type cannot change</strong>. The following could not be compiled:</p><pre>var x = 0<br>x = &quot;Evil String&quot;</pre><h4>Strongly typed</h4><p>Furthermore, Swift is strongly typed. This means you cannot e.g. call a function that expects a String with an Int value. Because it’s statically typed the language already knows all the types before compile time, so it can shout at you before even doing the hard work.</p><h3>What’s an Optional?</h3><p>Let’s imagine we work on an app that deals with GitHub user profiles. Each user must have a username and <em>optionally</em> have a bio. The JSON representation of a user could look like this:</p><pre>{<br>  &quot;username&quot;: &quot;slashmo&quot;,<br>  &quot;bio&quot;: &quot;Freelance iOS-Developer&quot;<br>}</pre><p>If we were to write a Swift user type our first attempt could be this:</p><pre>struct User {<br>  let username: String<br>  var bio: String<br>}<br><br>let user = User(username: &quot;slashmo&quot;, bio: &quot;Freelance iOS-Developer&quot;)</pre><p>But, as stated above the bio of a user could also be empty, or nil in Swift terms. Our current User struct is not able to provide us with this functionality:</p><pre>let user = User(username: &quot;slashmo&quot;, bio: nil)</pre><p>The reason for this is actually pretty simple. As you now know Swift is strongly typed, so it expects a value of type String for the bio property, because we explicitly said so in its declaration. And because nil is not a String value the compiler doesn’t want to compile it.</p><h4>The Optional type</h4><p>For such use cases, Swift has a specific type, the Optional&lt;Wrapped&gt;. It’s an enumeration that’s generic over Wrapped. The enumeration consists of two cases, .none and .some(Wrapped).</p><blockquote>Put simply, an Optional is like a box that either holds a value or nothing. The Optional works with every other type by wrapping the optional value inside. This means you can have Optional Strings, Optional Ints, Optional Users and even Optional Optionals. 🔥</blockquote><p>And because it’s just another type we can use it to declare variables, constants, and functions, just like String, Int, …</p><p>Applied to the GitHub example our User struct now looks like this:</p><pre>struct User {<br>  let username: String<br>  var bio: Optional&lt;String&gt;<br>}<br><br>let user = User(username: &quot;slashmo&quot;, bio: .none)<br>let nerd = User(username: &quot;slashmo&quot;, bio: .some(&quot;Freelance iOS-Developer&quot;))</pre><h4>Syntax Sugar</h4><p>To be honest, the above doesn’t look as <em>Swifty</em> as we’re used to. Especially the .some case with its associated String is unnecessarily verbose because it’s quite obvious that we have <em>some</em> value if a String is associated with it 😊. Also, it’s a bit tedious to always declare optional types as Optional&lt;Wrapped&gt;.</p><p>There is a far simpler way to declare Optionals and set their values:</p><pre>struct User {<br>  let username: String<br>  var bio: String?<br>}<br><br>let user = User(username: &quot;slashmo&quot;, bio: nil)<br>let nerd = User(username: &quot;slashmo&quot;, bio: &quot;Freelance iOS-Developer&quot;)</pre><p>By suffixing any type with ? we wrap it inside an Optional type. And because Optional conforms to ExpressibleByNilLiteral the .none case can be expressed as nil. Optional also has an initializer taking a non-optional instance of Wrapped which lets us skip the .some if we have a value. Much nicer, isn’t it? 💅</p><h3>How can we work with optional values?</h3><p>Now that we’re able to declare Optionals the next step is to actually work with them. Let’s say, e.g. that in our imaginary GitHub app we want to show the bio on a users profile if it’s set.</p><blockquote>Before we can use a value wrapped inside an Optional we first have to unwrap it (get it out of the box).</blockquote><p>There are several ways to unwrap an Optional. I’ll explain them one by one and compare the different approaches along the way.</p><h4>Forced unwrapped Optional</h4><p>The first one I’m going to show you is the <strong>forced unwrapped Optional</strong>.</p><pre>bioLabel.text = user.bio!</pre><p>The ! after the property tells the compiler that we are 100% sure that user.bio holds a value, or in other words that it is not nil. The result of this expression is the unwrapped String which we can assign to the labels text property.</p><p>If, in the above snippet, the users’ bio were nil our <strong>program would crash</strong> and throw this message:</p><p><em>Unexpectedly found nil while unwrapping an Optional.</em></p><p>To avoid this from happening we could first check if the Optional is nil and then force-unwrap the value only if the check was successful:</p><pre>if user.bio != nil {<br>  bioLabel.text = user.bio!<br>} else {<br>  // bio is nil, hide the label<br>}</pre><p>Again, this is not very <em>Swifty</em> because we basically repeat ourselves unnecessarily. First, we check that the Optional is not nil, but then we have to force-unwrap it anyways.</p><h4>Optional binding</h4><p>As hinted above, there’s a more elegant solution. Optional binding allows us to <em>bind</em> a value of an Optional, if one exists, to a constant or variable.</p><pre>if let bio = user.bio {<br>  bioLabel.text = bio<br>} else {<br>  // bio is not available in here, because user.bio is nil<br>}</pre><p>Now, we don’t have an explicit condition but rather an assignment to a new constant called bio. This constant is only available inside the if-block and it holds the unwrapped value. Not only is this more readable than the previous example, but it also gives us the benefit of only unwrapping once. Let’s say we wanted to use the users’ bio twice. In the case of force-unwrapping, we’d have to write the ! for each usage. With optional binding, we unwrap once and use the new constant every time we want to use the value.</p><h4>Optional binding with early exit</h4><p>Depending on the use case, the if let-block can get quite large, often times larger than the else-block. In this case, we might want to use a guard let instead which gives us the benefit of not having to go one indentation level deeper just to access an Optionals value.</p><pre>guard let bio = user.bio else {<br>  // bio is not available here, because user.bio is nil<br>  return<br>}<br>bioLabel.text = bio</pre><p>As you can see, the bio constant is now available in the same scope. Keep in mind that with guard statements we always have to have an else clause, which comes first, hence the name <em>early exit</em>. This else clause <strong>has to exit</strong> unless we call a non-returning function like fatalError().</p><h4>Nil-coalescing</h4><p>What if we want to show a default text if the users’ bio is nil?</p><pre>if let bio = user.bio {<br>  bioLabel.text = bio<br>} else {<br>  bioLabel.text = &quot;No bio&quot;<br>}</pre><p>This looks quite verbose. We repeated the assignment part, only to set a different value depending on the Optional’s case. Normally, we would use a ternary operation in such a case to clean things up a bit:</p><pre>bioLabel.text = user.bio != nil ? user.bio! : &quot;No bio&quot;</pre><p>Although this works it’s also not that clear, because we first check if the Optional is nil and then force-unwrap the value if that’s not the case. Swift provides another way by introducing the <em>Nil-coalescing operator</em>.</p><pre>bioLabel.text = user.bio ?? &quot;No bio&quot;</pre><p>This has the exact same result but now does the nil-check and unwrapping implicitly.</p><h4>Optional chaining</h4><p>For the sake of this example, let’s add an optional friend to our User type:</p><pre>struct User {<br>  // ...<br>  var friend: User?<br>}</pre><p>This friend is of type Optional&lt;User&gt; and therefore also has an optional bio. In another view of our imaginary app, we might want to show that friends bio if it’s available. With the power of optional binding we could come up with this:</p><pre>if let friend = user.friend {<br>  if let friendBio = friend.bio {<br>    friendBioLabel.text = friendBio<br>  }<br>}</pre><p>However, this doesn’t scale very well as it adds another level of indentation, although in the second scope we only use the friend constant to unwrap the second optional, their bio. Let’s think of this as a chain instead.</p><pre>user.friend?.bio</pre><p>Voilà, now we have optional chaining. Because friend is an Optional we can’t directly access it’s bio. Instead, we start an optional chain by writing a ? between each part of the chain.</p><p>We can use this optional chain in combination with optional binding and end up with a pretty elegant solution:</p><pre>if let friendBio = user.friend?.bio {<br>  friendBioLabel.text = friendBio<br>} else {<br>  // either friend or bio is nil. Which one is undefined<br>}</pre><p>Optional chains can be endless and also contain non-optional parts in between optional parts.</p><h4>Implicitly unwrapped Optional</h4><p>As you may already know, to successfully initialize an instance of any type, all its non-optional properties have to be set before returning from the initializer. In other words: If we want to create an instance without providing a default value to a property that property has to be an Optional. This means that we’d always have to unwrap this Optional where we want to use it. Because this can be very cumbersome in use-cases where we are 100% sure that a property holds a value (but it was not provided by us), instead of explicitly unwrapping it for every usage we can <strong>implicitly unwrap</strong> it by suffixing the type with ! instead of ?.</p><pre>@IBOutlet weak var bioLabel: UILabel!</pre><p>If you’re an iOS-Develop working in interface builder you know this kind of line. It creates a connection between your visual interface and your code. Now, because we cannot set the value itself it needs to be an Optional. If a connection is established the value will never be nil, so it’s safe to implicitly unwrap it. However, if the value is nil, e.g. if we forgot to create the connection, and we use the property <strong>the program will crash</strong>, giving us the same error message as the forced unwrapped Optional.</p><h3>Summary</h3><p>Now that you know what Optionals are all about and how to work with them let’s recap some of the key points of this post.</p><ul><li>Optional&lt;Wrapped&gt; is an enum with two cases: none &amp; some(Wrapped)</li><li>Optionals are declared by suffixing another type with ?: String?</li><li>Instead of writing .none we use nil: user.bio = nil</li><li>Instead of writing .some(&lt;value&gt;) we use &lt;value&gt;: user.bio = &quot;Bio&quot;</li><li>To access an Optional’s value we have to <strong>unwrap</strong> it</li><li>By suffixing an Optional variable / constant with ! we <strong>force-unwrap</strong> it, which causes the program to crash if it was nil instead</li><li>With the help of <strong>optional binding</strong> we are able to bind the unwrapped value to a new constant / variable to use it inside a block: if let friend = user.friend { print(friend) }</li><li>Optional binding works with both if &amp; guard</li><li>The <strong>nil-coalescing</strong> operator allows us to assign either the unwrapped value or a default value depending on the case of the Optional: label.text = user.bio ?? &quot;Default&quot;</li><li>With <strong>optional chaining</strong> we can create a call chain of optional variables, constants &amp; functions: user.friend?.bio?.uppercased</li><li>If we precede a type with ! instead of ? we create an implicitly unwrapped Optional, which force unwraps the Optional every time we use it automatically</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e88c2522663a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/slashkeys-development/the-optional-e88c2522663a">Optionals in Swift</a> was originally published in <a href="https://medium.com/slashkeys-development">Slashkeys Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apples WWDC Keynote in 400 words]]></title>
            <link>https://medium.com/code-university/apples-wwdc-keynote-in-400-words-53a9580b4740?source=rss-5f7b89e840d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/53a9580b4740</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[conference]]></category>
            <category><![CDATA[wwdc]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[apple]]></category>
            <dc:creator><![CDATA[Moritz Lang]]></dc:creator>
            <pubDate>Wed, 06 Jun 2018 10:31:51 GMT</pubDate>
            <atom:updated>2018-06-06T10:31:51.281Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vRkAZdL3FXSQPdXM" /><figcaption>Photo by <a href="https://unsplash.com/@tylercallahan?utm_source=medium&amp;utm_medium=referral">Tyler Callahan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This Monday, Apple kicked off their annual developers’ conference in San Jose. Here’s what you need to know in <strong>exactly 400 words</strong>:</p><h4>iOS 12</h4><p>Starting with <a href="https://www.apple.com/ios/ios-12-preview/">iOS 12</a>, the tech company announced that this years mobile OS release is all about <strong>performance</strong>, resulting in faster app starts, faster camera access and a faster keyboard display. Especially on <strong>old devices</strong>, going back as far as the iPhone 5s, this is claimed to make a huge difference. <strong>FaceTime</strong> supports up to 32 people in <strong>group calls</strong>. The same augmented reality environment can be experienced by multiple people simultaneously and shared via Messages and Mail. <strong>Notifications</strong> will be <strong>grouped</strong> by threads and topics and Animoji’s have a customizable version called Memoji. <strong>Photos</strong> recommends sharing to specific contacts and features a smarter <strong>search</strong> with support for <strong>multiple keywords</strong>. Screen Time shows how much you use each app and following last year’s acquisition of <a href="http://my.workflow.is/">Workflow</a> Apple integrated the service into <strong>Siri</strong> and renamed it <strong>Shortcuts</strong>, allowing you to <strong>automate</strong> <strong>common tasks</strong> on your iOS device.</p><h4>watchOS 5</h4><p>Secondly, <a href="https://www.apple.com/watchos-preview/">watchOS 5</a> introduced a new <strong>Walkie Talkie</strong> feature, workout modes for <strong>Yoga &amp; Hiking</strong>, <strong>Podcasts</strong>, <strong>competitions</strong>, and a tiny <strong>web browser</strong> powered by WebKit.</p><h4>tvOS</h4><p>The third and probably smallest update was <a href="https://www.apple.com/apple-tv-4k/">tvOS</a> with added support for <strong>Dolby Atmos</strong>, a <strong>remote inside the iOS control center</strong>, and location descriptions of the screensaver landscapes.</p><h4>macOS Mojave</h4><p>Last but not least there was <a href="https://www.apple.com/macos/mojave-preview/">macOS Mojave</a> with a new <strong>dark mode</strong>, a <strong>desktop</strong> that <strong>cleans itself</strong> by putting files into stacks. It also adds Quick Actions based on the selected files type and a sidebar viewing metadata to Finder. Quick Look now lets you perform tasks on a file without having to open the full app. <strong>Screenshots</strong> now look <strong>similar to iOS</strong>, enabling you to <strong>directly edit and share</strong> them without having to save them to disk. With Continuity Camera you can <strong>scan documents on iOS</strong> and automatically <strong>paste them to your Mac</strong>. As a preview of iOS apps running on macOS the Mac now includes News, Stocks, Home, and Voice Memos. The <strong>Mac App Store</strong> got a <strong>full re-design</strong> gaining video previews and a review system. It also improves <strong>Privacy &amp; Security</strong> by prompting you to grant access to the camera, microphone, Messages history, and Mail database. <strong>Safari</strong> detects social media Like buttons, Share buttons, or comment widgets and <strong>prevents third parties from tracking you</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53a9580b4740" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-university/apples-wwdc-keynote-in-400-words-53a9580b4740">Apples WWDC Keynote in 400 words</a> was originally published in <a href="https://medium.com/code-university">CODE University of Applied Sciences</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical Key Paths in Swift]]></title>
            <link>https://medium.com/slashkeys-development/practical-keypaths-in-swift-220da5ab5950?source=rss-5f7b89e840d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/220da5ab5950</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Moritz Lang]]></dc:creator>
            <pubDate>Thu, 31 May 2018 22:47:24 GMT</pubDate>
            <atom:updated>2018-06-27T23:08:42.418Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Rew-RW28FRMRvN9y" /><figcaption>A key in front of a path, found on <a href="https://unsplash.com/@katybelcher?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Although Key Paths are one of the most popular features introduced by Swift 4 I always struggled to integrate them in my day-to-day code. That’s why, in this post, I challenged myself to write about <strong>3 practical use-cases of Key Paths</strong>. Before reading on I recommend to first learn about <a href="https://blog.slashkeys.com/swift-generics-introduction-a621af69ff9f">Generics</a> &amp; <a href="https://blog.slashkeys.com/generic-types-type-constraints-b1b40ad8b890">Generic types</a>.</p><h4>1. Vapor Validation</h4><p>I discovered this first example while skimming through Vapor 3 on <a href="https://github.com/vapor">GitHub</a>. They’ve written a very elegant validation API which uses Key Paths to add specific fields with their respective rules to the validation process of a specific type. Complicated enough? 😊 Let’s take a look!</p><pre>class User: Validatable, Reflectable, Codable {<br>  var name: String<br>  var age: Int<br><br>  init(name: String, age: Int) {<br>    self.name = name<br>    self.age = age<br>  }<br><br>  static func validations() throws -&gt; Validations&lt;User&gt; {<br>    var validations = Validations(User.self)<br>    // validate name is at least 5 characters and alphanumeric<br>    try validations.add(\.name, .count(5...) &amp;&amp; .alphanumeric)<br>    // validate age is 18 or older<br>    try validations.add(\.age, .range(18...))<br>    return validations<br>  }<br>}</pre><p>In this small excerpt of a unit test inside Vapor’s <a href="https://github.com/vapor/validation">Validation library</a>, they used a combination of Key Paths and static, generic constrained, extensions on the Validator type to add validations to the User class. The add method is declared like this:</p><pre>public mutating func add&lt;T&gt;(_ keyPath: KeyPath&lt;M, T&gt;, _ validator: Validator&lt;T&gt;) throws</pre><p>As you can see the associated type of Validator is inferred by the Key Path to provide you with different Validator extensions based on the Key Paths value type. 🧙‍♀️</p><blockquote>In case you’re wondering about the mysterious M, it’s an associated type of the Validations type.</blockquote><h4>2. AutoLayout wrapper</h4><p>I stumbled across this gem while watching another awesome episode of <a href="https://talk.objc.io/episodes/S01E75-auto-layout-with-key-paths">Objc.io ’s Swift Talk</a>. As part of the episode, they wrote convenience methods to work with AutoLayout in iOS. At the end they created a tiny wrapper for NSLayoutConstraint which can be used like this:</p><pre>superView.addSubview(subview, constraints: [<br>  equal(\.centerXAnchor),<br>  equal(\.centerYAnchor)<br>])</pre><p>The implementation of equal(_:) looks like the following:</p><pre>typealias Constraint = (_ child: UIView, _ parent: UIView) -&gt; NSLayoutConstraint<br><br>func equal&lt;L, Axis&gt;(_ to: KeyPath&lt;UIView, L&gt;) -&gt; Constraint where L: NSLayoutAnchor&lt;Axis&gt; {<br>  return { view, parent in<br>    view[keyPath: to].constraint(equalTo: parent[keyPath: to])<br>  }<br>}</pre><p>As already seen in the first example the generic Axis is inferred by the KeyPath and then passed along as the associated type of NSLayoutAnchor.</p><h4>3. Identifiable with custom property</h4><pre>protocol Identifiable {<br>  associatedtype ID<br>  static var idKey: KeyPath&lt;Self, ID&gt; { get }<br>}<br><br>extension Identifiable where ID: Equatable {<br>  static func ==(lhs: Self, rhs: Self) -&gt; Bool {<br>    return lhs[keyPath: Self.idKey] == rhs[keyPath: Self.idKey]<br>  }<br>}<br><br>struct User: Identifiable {<br>  static let idKey = \User.id<br>  let id: String<br>}<br><br>struct Car: Identifiable {<br>  static let idKey = \Car.licensePlate<br>  let licensePlate: String<br>}<br><br>let user = User(id: &quot;abc&quot;)<br>let otherUser = User(id: &quot;def&quot;)<br>user == otherUser<br><br>let car = Car(licensePlate: &quot;AB-CD-1234&quot;)<br>let otherCar = Car(licensePlate: &quot;EF-GH-5678&quot;)<br>car == otherCar</pre><p>In this last example, I used a KeyPath to set the ID type on conforming types of Identifiable based on the idKey. Now, instead of having to use an id key on every object that should be identifiable I can choose whatever fits best into the context. As an added bonus I added conformation to Equatable whenever the ID conforms to it. Inside the function, I then used the idKey to retrieve the underlying value.</p><h4>4. Your turn</h4><p>What about you? What’re your favorite use-cases of Key Paths in Swift? I’d love to extend this list 😊</p><h4>Conclusion</h4><p>Hopefully, this post gave you a brief overview of some more real-life examples of Key Paths. It sure helped me to understand them better.</p><p><strong>Thanks for reading and happy coding</strong> ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=220da5ab5950" width="1" height="1" alt=""><hr><p><a href="https://medium.com/slashkeys-development/practical-keypaths-in-swift-220da5ab5950">Practical Key Paths in Swift</a> was originally published in <a href="https://medium.com/slashkeys-development">Slashkeys Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing delegates in Swift]]></title>
            <link>https://medium.com/slashkeys-development/testing-delegates-in-swift-cc272d6859f0?source=rss-5f7b89e840d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc272d6859f0</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[delegation]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[Moritz Lang]]></dc:creator>
            <pubDate>Sat, 24 Mar 2018 19:17:47 GMT</pubDate>
            <atom:updated>2018-03-24T19:19:07.581Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WDz3vF1CCFyA6FYe." /><figcaption>“A clock hanging on the train station platform.” by <a href="https://unsplash.com/@lum3n?utm_source=medium&amp;utm_medium=referral">LUM3N</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It’s all about the consumer 🎧</p><p>In my <a href="https://blog.slashkeys.com/delegation-pattern-in-swift-50141cc689ae">last post</a> I explained the concept of Delegation using Swift. If you’re unfamiliar with this concept or never even heard of it I recommend checking it out before reading this piece. I also assume that you have at least basic knowledge of unit testing. In the following few sentences I’ll give my best to show my approach of writing tests against code which uses the Delegation pattern.</p><h3>It’s all about the consumer</h3><p>As I mentioned before the Delegation pattern consists of two parts: A <strong>producer</strong> and a <strong>consumer</strong>. The procucer TwitterAPI produces events / values which the consumer FeedViewModel consumes. The consumer does so by setting itself as the delegate-property of the producer which the producer calls methods on to emit those events.</p><h3>Synchronous unit tests</h3><p>The <em>tipical</em> unit test arranges input, executes something with the SUT (subject under test) and asserts on the output. Here is a basic example of a test for a fictual `sum` method.</p><pre>func testItAddsTwoNumbers() {<br>  // arrange<br>  let x = 1<br>  let y = 2<br>  let expectedSum = 3</pre><pre>  // act<br>  let sum = sum(x, y)</pre><pre>  // assert<br>  XCTAssertEqual(sum, expectedSum)<br>}</pre><p>As sum is <strong>synchronous</strong> and directly returns the value we can easily assign its result to a new constant to assert on.</p><h3>Asynchronous unit tests</h3><p>Writing unit tests for TwitterAPI may not be that trivial at first, because it’s asynchronous and its methods don’t return any values directly. The only output we have are the calls of the methods the consumer implemented.</p><p>As you probably already guessed we need a consumer in our tests. Let’s get straight to the code which I’ll explain afterwards.</p><pre>class TwitterAPIConsumerMock: TwitterAPIDelegate {<br>  var didRetrieveTweetsClosure: (([Tweet]) -&gt; Void)?</pre><pre>  func didRetrieveTweets(_ tweets: [Tweet]) {<br>    didRetrieveTweetsClosure(tweets)<br>  }<br>}</pre><p>Here I defined a new class called TwitterAPIConsumerMock which conforms to TwitterAPIDelegate. Besides the required method didRetrieveTweets I also added the didRetrieveTweetsClosure that will come in handy in a bit. All didRetrieveTweets does is to pass through the retrieved tweets to the closure.</p><pre>func testItNotifiesItsConsumerOnceNewTweetsWereRetrieved() {<br>  // 1<br>  let expectedTweets = [<br>    Tweet(from: &quot;slashmodev&quot;, content: &quot;Testing Delegates in Swift&quot;)<br>  ]</pre><pre>  // 2<br>  let tweetsExpectation = expectation(&quot;TwitterAPI retrieved new tweets&quot;)</pre><pre>  // 3<br>  let twitterAPI = TwitterAPI()<br>  let consumer = TwitterAPIConsumerMock()<br>  twitterAPI.delegate = consumer</pre><pre>  consumer.didRetrieveTweetsClosure = { tweets in<br>    XCTAssertEqual(tweets, expectedTweets)<br>    tweetsExpectation.fulfill()<br>  }</pre><pre>  // 4<br>  twitterAPI.getTweets()</pre><pre>  waitForExpectations(timeout: 1.0)<br>}</pre><h4>1. Define input</h4><p>In our test method we start by defining an array of expected tweets. We could pass this array into a test implementation of a network service. John Sundell <a href="https://www.swiftbysundell.com/posts/mocking-in-swift">wrote about this</a> in much more detail.</p><h4>2. Set our expectations</h4><p>In the next line call expectation to add a new expectation to our test method. In the last line you can see that we wait for all added expectations to fulfill (with a timeout of 1 second).</p><h4>3. Set up the SUT</h4><p>Then we create instances of both TwitterAPI and the newly created TwitterAPIConsumerMock and set the latter as Delegate of twitterAPI. Coming to the more interesting part we assign a new closure to the consumers didRetrieveTweetsClosure property which whithin we first compare the tweets to the ones we expected and finally fulfill the expectation.</p><h4>4. Kick off the process</h4><p>As the last step we call twitterAPIs getTweets method to kick off the process. Once the Delegate is called it calls the closure which then fulfils the expectation after asserting on the value.</p><p>By fulfilling the expectation only if didRetrieveTweets is called we can ensure that our test fails if that’s not the case.</p><h3>Summary</h3><p>Introducing an intermediary type with closure properties as the consumer, is in my oppinion a very simple way to write tests against an asynchronous, Delegation-based API.</p><p>What do you think about this approach? Do you use other techniques or did you come up with the same one?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc272d6859f0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/slashkeys-development/testing-delegates-in-swift-cc272d6859f0">Testing delegates in Swift</a> was originally published in <a href="https://medium.com/slashkeys-development">Slashkeys Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Delegation pattern in Swift]]></title>
            <link>https://medium.com/slashkeys-development/delegation-pattern-in-swift-50141cc689ae?source=rss-5f7b89e840d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/50141cc689ae</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[delegate]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[protocol]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Moritz Lang]]></dc:creator>
            <pubDate>Thu, 15 Feb 2018 12:23:15 GMT</pubDate>
            <atom:updated>2018-02-15T12:50:30.450Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sHViiiyBpGINtmGQ." /><figcaption>DePhoto by <a href="https://unsplash.com/@jasonrosewell?utm_source=medium&amp;utm_medium=referral">Jason Rosewell</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>How children should talk to their parents 👨‍👩‍👧‍👦</p><p>Let’s imagine we have two objects, FeedViewModel &amp; TwitterAPI. An instance of TwitterAPI is stored as a property called twitterAPI inside the FeedViewModel:</p><pre>class TwitterAPI {}</pre><pre>class FeedViewModel {<br>  <strong>private let twitterAPI = TwitterAPI()</strong><br>}</pre><p>Sending a message from FeedViewModel to TwitterAPI is fairly easy as we can call a method or set a property on twitterAPI, but communicating back from TwitterAPI to FeedViewModel is a bit more complex, because it doesn’t have a direct connection to FeedViewModel.<br>Of course we could add this connection by adding a property feedViewModel: FeedViewModel to TwitterAPI, but this isn’t really flexible as we might want to use the TwitterAPI in other scenarios where the parent object is no FeedViewModel. In that case we would have to add a property for each use-case of TwitterAPI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J02IfjE5Kx3DeXwoBY3orw.png" /><figcaption>Currently no connection from TwitterAPI to FeedViewModel exists. 💔</figcaption></figure><p>One possible solution is to use the <strong>Delegation pattern</strong>.</p><h3>It all starts with a protocol</h3><pre>protocol TwitterAPIDelegate: class {<br>  func didRetrieveTweets(_ tweets: [Tweet])<br>}</pre><p>Now we can add a property (usually called delegate) to TwitterAPI:</p><pre>class TwitterAPI {<br>  <strong>weak var delegate: TwitterAPIDelegate?</strong><br>}</pre><p>By setting the type of <em>delegate</em> to <em>TwitterAPIDelegate</em> we can ensure that the value it stores implements all methods required by the protocol. By <strong>extending</strong> <em>FeedViewModel</em> <strong>to conform to</strong> <em>TwitterAPIDelegate</em> it becomes one possible candidate for this value.</p><blockquote>You may have noticed that delegate is a weak property. This is used to avoid a retain cycle between FeedViewModel and TwitterAPI. You can read more about retain cycles and Swift’s memory management in an upcoming post. For now just keep in mind that we need to add the : class requirement to the delegate so that we can make the property weak.</blockquote><p>Via an extension on FeedViewModel we can add the implementation for didRetrieveTweets.</p><pre>extension FeedViewModel: TwitterAPIDelegate {<br>  func didRetrieveTweets(_ tweets: [Tweet]) {<br>    // display the tweets<br>  }<br>}</pre><p>Inside FeedViewModel&#39;s initializer we can set itself as the value of twitterAPI&#39;s delegate property:</p><pre>class FeedViewModel {<br>  private let twitterAPI = TwitterAPI()<br>  init() {<br>    <strong>twitterAPI.delegate = self</strong><br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lm_EyW1BtsTpjI7j5i54Zw.png" /><figcaption>The delegate property now connects TwitterAPI to FeedViewModel ❤️</figcaption></figure><h3>Using our newly created connection</h3><p>Now that we established the missing connection we can notify FeedViewModel about events from TwitterAPI by simply calling the methods on delegate.</p><pre>class TwitterAPI {<br>  weak var delegate: TwitterAPIDelegate?<br>  func connect() {<br>    // do some network calls ⏱<br>    <strong>delegate?.didRetrieveTweets(tweets)<br> </strong> }<br>}</pre><p>Because the value of delegate is set to FeedViewModel&#39;s self the view model’s implementation of didRetrieveTweets will be called. 🧙‍♀️</p><h3>Conclusion</h3><p>As you can see the Delegation pattern is a simple, yet elegant, solution for communication between child-objects and their parents / owners.</p><p>What do <strong>you</strong> think about this approach? Do you still have some questions left or do you prefer other solutions over this?</p><p>Thanks for reading ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50141cc689ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/slashkeys-development/delegation-pattern-in-swift-50141cc689ae">Delegation pattern in Swift</a> was originally published in <a href="https://medium.com/slashkeys-development">Slashkeys Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to properly setup your new Mac]]></title>
            <link>https://medium.com/slashkeys-development/how-to-properly-setup-your-new-mac-e19bfe0307cf?source=rss-5f7b89e840d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e19bfe0307cf</guid>
            <category><![CDATA[computers]]></category>
            <category><![CDATA[homebrew]]></category>
            <category><![CDATA[mac]]></category>
            <dc:creator><![CDATA[Moritz Lang]]></dc:creator>
            <pubDate>Sat, 22 Jul 2017 13:37:17 GMT</pubDate>
            <atom:updated>2017-08-23T20:31:58.288Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*79_kW-JZ0chvYF0-I9Cu_A.jpeg" /><figcaption><a href="https://www.pexels.com/photo/white-black-laptop-computer-487812/">Source</a></figcaption></figure><p>Using a Brewfile to track installed applications</p><p>Since I got my first mac in Mid 2014 I got used to reset it once the next macOS was released. This routine ensures that my MacBook is always running pretty smooth. There was just one problem with this routine:</p><blockquote>I had to manually reinstall every program after the hard reset.</blockquote><h4>The solution: <a href="https://github.com/rcmdnk/homebrew-file">homebrew-file</a></h4><p>homebrew-file is a plugin for the famous dependency manager homebrew which allows you to track all installed <em>brews</em> in a single Git repository.</p><h4>How to get started</h4><p>Before we do anything, let’s <strong>make sure we have a time machine backup.</strong><br><em>Unless, of course, you got your first Mac </em>😊</p><h4>Hard reset</h4><p>Now we can restart the Mac and hold cmd + r until the macOS recovery window pops up. After that we can reformat the disc to delete all data with the disc utility app. The only thing left to do is to go back, click on “reinstall macOS” and wait for the os to be downloaded. <em>Depending on your internet connection this can take up to multiple hours, so make sure you’re prepared to wait</em> ☕️</p><h4>Install the command line tools</h4><p>Welcome to your fresh installation of macOS 🚀 The first thing to do is to open Terminal and run the following command to install the command line tools: sudo xcode-select --install</p><h4>Install homebrew &amp; homebrew-file</h4><p><strong>homebrew-file</strong> comes with a handy script which allows us to install both homebrew<strong> </strong>&amp; homebrew-file<strong> </strong>itself: curl -fsSL <a href="https://raw.github.com/rcmdnk/homebrew-file/install/install.sh">https://raw.github.com/rcmdnk/homebrew-file/install/install.sh</a> |sh</p><h4>Initialize the Brewfile</h4><p>Before this step we have to create a Git repository on Github, Gitlab, or anything else. This repo can be public if you like to show of the programs you work with, but it doesn’t have to be.<br>With brew file set_repo we can now setup a <strong>Brewfile</strong> for this repository and with brew file init we are able to finalize the setup.</p><h4>Update the Brewfile</h4><p>After the successful setup we can use hombrew as we are used to do. Usually the first thing I install is <strong>git</strong>.<br>brew install git &amp;&amp; brew file update … brew file update updates, as the name suggests, the Brewfile and automatically pushes the changes to the git repo after commiting the changes.</p><h4>Install applications with brew cask and mas</h4><p>Well, git is only a command line tool, so you may ask yourself how to add “real” applications like Visual Studio Code. This is as easy as running brew cask install visual-studio-code <br>Also you may have some applications installed through the Mac App Store. For this purpose a tool called <a href="https://github.com/mas-cli/mas">mas</a> was created. It allows you to search, install and update applications from the Mac App Store right inside your Terminal. It also goes pretty well with homebrew-file. You just have to install mas (brew install mas) and update your Brewfile.</p><p><em>Thanks to </em><a href="https://twitter.com/marcelzimmer"><em>Marcel</em></a><em> for pointing out that this section was missing</em> 👍🏻</p><h4>Recap</h4><p>Now, once a new macOS version was released, all that’s left to do is:</p><ol><li>Reset the Mac</li><li>Install the command line tools</li><li>Install homebrew and homebrew-file</li><li>Clone the Brewfile with brew file set_repo &amp; brew file init</li><li>Install all <em>brews</em> from our Brewfile with brew file install</li><li>🚀🎉🕺🏽</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e19bfe0307cf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/slashkeys-development/how-to-properly-setup-your-new-mac-e19bfe0307cf">How to properly setup your new Mac</a> was originally published in <a href="https://medium.com/slashkeys-development">Slashkeys Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing a Custom Conditional Vue Directive]]></title>
            <link>https://medium.com/slashkeys-development/custom-conditional-vue-directive-2decca529b80?source=rss-5f7b89e840d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2decca529b80</guid>
            <category><![CDATA[directives]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Moritz Lang]]></dc:creator>
            <pubDate>Tue, 28 Feb 2017 22:31:52 GMT</pubDate>
            <atom:updated>2017-02-28T22:36:31.034Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L1r0srbSZKY52TWjr9yTeg.jpeg" /></figure><h4>Just another fancy post title.</h4><h4><strong>The task</strong></h4><p>There is a modal component on the page I’m currently working on. The modal contains a set of textfields which are generated using v-for over the fields property to keep it dynamic. When toggling the modal the <em>first </em>textfield should be focused automatically.</p><p>The first, very trivial, solution I tried was to set the input to <strong>autofocus</strong> if the textfield’s index equals 0. It looked like the following snippet:</p><pre>&lt;div <strong>v-for</strong>=&quot;(<strong>field</strong>, <strong>index</strong>) in <strong>fields</strong>&quot;&gt;<br>  &lt;input <strong>type</strong>=&quot;text&quot; <strong>v-if</strong>=&quot;<strong>index</strong> === <strong>0</strong>&quot; <strong>autofocus</strong>&gt;<br>  &lt;input <strong>type</strong>=&quot;text&quot; <strong>v-else</strong>&gt;<br>&lt;/div&gt;</pre><p>This “solution” actually kind of worked, but only on the initial page load. If I were to open, close &amp; reopen the modal the focus would not be set.</p><h4>The final solution</h4><p>The solution I finally came up with is in my opinion pretty cool &amp; flexible. Basically I wrote a custom directive named v-focus which set’s the element it is set on focused, only if the passed expression evaluates to true. This allows me to shorten the above snippet to this simple one-liner:</p><pre>&lt;input <strong>type</strong>=&quot;text&quot; <strong>v-for</strong>=&quot;(<strong>field</strong>, <strong>key</strong>) in <strong>fields</strong>&quot; <strong>v-focus</strong>=&quot;<strong>key</strong> === <strong>0</strong>&quot;&gt;</pre><p>I think for this example the code says more than thousand words, so here it is 😊</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2Fslashmo%2Fmxf6q8e1%2Fembedded%2F&amp;url=https%3A%2F%2Fjsfiddle.net%2Fslashmo%2Fmxf6q8e1%2F&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2F72f3fe3c06b77d628290e4fdd8aab746%2F%3Fdefault%3D%26s%3D80&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/860f6dbcbd6c99e5b9a00d2415afd339/href">https://medium.com/media/860f6dbcbd6c99e5b9a00d2415afd339/href</a></iframe><p>Please feel free to give me your feedback for the final solution &amp; fork it on JSFiddle.</p><p>To finally wrap up this post I just want to point out how much I like <a href="https://github.com/vuejs/vue">VueJS</a> &amp; it’s new, but simple and powerful, ecosystem incl. <a href="https://github.com/vuejs/vue-router">VueRouter</a> &amp; <a href="https://github.com/vuejs/vuex">VueX</a>.</p><p>Have a nice day / night &amp; happy coding! ✌🏻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2decca529b80" width="1" height="1" alt=""><hr><p><a href="https://medium.com/slashkeys-development/custom-conditional-vue-directive-2decca529b80">Writing a Custom Conditional Vue Directive</a> was originally published in <a href="https://medium.com/slashkeys-development">Slashkeys Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Higher order FUNctions in Swift]]></title>
            <link>https://medium.com/slashkeys-development/swift-map-vs-flatmap-258d21f714ad?source=rss-5f7b89e840d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/258d21f714ad</guid>
            <category><![CDATA[higher-order-function]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Moritz Lang]]></dc:creator>
            <pubDate>Thu, 01 Dec 2016 23:22:41 GMT</pubDate>
            <atom:updated>2016-12-09T17:40:06.374Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XsCKmPXNEOKvgykwgYXiPQ.jpeg" /><figcaption>a pretty flat map</figcaption></figure><h4>map vs. flatMap</h4><p>Did you ever wonder about the difference between map &amp; flatMap? Well, in this post I want to show you some use cases on when to call which function. It’s actually pretty easy to understand. 😊</p><h3>The example</h3><p>In my example we declared the following two types:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b9366de4a53cadc1781c77ef38ae492/href">https://medium.com/media/7b9366de4a53cadc1781c77ef38ae492/href</a></iframe><p>Nothing new so far and pretty lame code. Now let’s continue with the fun part:</p><h3><strong>Challenge #01</strong></h3><blockquote>Retrieve an array containing all firstNames from the people array.</blockquote><p>This one is actually pretty easy. We just have to call map on people and return the firstName property like so:</p><pre><strong>let</strong> firstNames = people.<strong>map</strong> { $0.firstName }</pre><p>The result is an array of Strings —how cool is that?! :)</p><h3>Challenge #02</h3><blockquote>Retrieve an array containing all names from the products array of every <em>person </em>in people.</blockquote><p>Let’s try our luck by using map again. First we would try to get an array containing all products. Maybe we try something like this:</p><pre><strong>let</strong> allProducts = people.<strong>map</strong> { $0.products }</pre><p>Now we have a little problem: allProducts is an <strong>array of arrays of products</strong>. This makes totally sense as we map over each persons products array and append that array to our resulting array allProducts. <br>To join those arrays we could call joined() on allProducts and use map one last time to get an array of all product names:</p><pre><strong>let</strong> allProducts = people.<strong>map</strong> { $0.products }<br><strong>let</strong> joinedProducts = allProducts.<strong>joined()</strong><br><strong>let</strong> productNames = joinedProducts.<strong>map</strong> { $0.name }</pre><p>This works as expected but is not so nice to read. The fact that we have to manually create <strong>3 arrays</strong> looks very bad.</p><h3>flatMap</h3><p>Of course there is a much better solution just waiting to be used: flatMap looks very similar too map. But there is one crucial difference.</p><p>map transforms an array and appends it to a resulting array. This works fine if the resulting array isn’t another array by itself.</p><p>flatMap transforms an array and appends it to a resulting array just like map. But after that it joins all arrays in the resulting arrays.</p><p>Seems like this is the perfect fit in our case, so let’s try it out:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/176e38dfa67a949352fa8c69455e18bc/href">https://medium.com/media/176e38dfa67a949352fa8c69455e18bc/href</a></iframe><p>Very cool, hm? flatMap returns an array containing all products. On this array we then call map to get the name of each product.</p><p>I hope all those arrays didn’t confuse you too much and I think it’s the best to write the example by yourself in a Playground and experiment a little bit with it.</p><p>Good luck &amp; happy coding 🎄</p><p><em>If you enjoyed reading this post hit the </em>❤️<em> button and share it on </em><a href="http://twitter.com/moritzlang97"><em>Twitter</em></a><em>, Facebook or wherever you want </em>😊✌🏻</p><blockquote><a href="https://medium.com/u/e907069a5fc9"><em>Yasmin</em></a><em>, thank you very much for correcting my grammar once more 😇<br></em><a href="https://medium.com/u/89e88798c91b">Bob</a>, thank you for mentioning me in your recent posts <em>✌🏻</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=258d21f714ad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/slashkeys-development/swift-map-vs-flatmap-258d21f714ad">Higher order FUNctions in Swift</a> was originally published in <a href="https://medium.com/slashkeys-development">Slashkeys Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to unwrap Optionals in Swift]]></title>
            <link>https://medium.com/slashkeys-development/how-to-unwrap-optionals-in-swift-33441c9d9106?source=rss-5f7b89e840d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/33441c9d9106</guid>
            <category><![CDATA[optionals]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Moritz Lang]]></dc:creator>
            <pubDate>Sun, 28 Aug 2016 11:40:01 GMT</pubDate>
            <atom:updated>2016-12-02T09:55:03.494Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*22edlJO3CJXyWYO2jYr80Q.jpeg" /></figure><p>Talking about different solutions for unwrapping optionals.</p><p>First things first: <strong>What the hell is unwrapping at all?!</strong></p><p>Well, in Swift we <em>luckily </em>have a feature called Optionals. <br>An Optional can either be <strong>nil </strong>or <strong>some value</strong>. In the Swift language this is represented by an enum with two cases: <em>None</em><strong><em> </em></strong>or <em>Some. </em>Optional looks like this:</p><pre>public enum Optional&lt;Wrapped&gt; : _Reflectable, NilLiteralConvertible {<br>    case None<br>    case Some(Wrapped)<br>    // Some more stuff follows here<br>}</pre><p>We can see that the enum has an associated type called <em>Wrapped</em>, which is just a generic placeholder for whatever type we want to use with the Optional enum. Because of that Optionals can declared in many ways:<br><strong>String?</strong><em> </em>for example is just a shorthand form of <strong>Optional&lt;String&gt;</strong>. Also <strong>nil</strong> is just an alias for the enum case <strong>.None</strong>, which we get through the protocol <strong>NilLiteralConvertible</strong>.</p><h3>Unwrapping</h3><p>Now that you <em>hopefully</em> understand, how to wrap a value inside an Optional, I want to show you how to get it out again. This term is simply called <em>Unwrapping</em>. There are mainly 3 ways of unwrapping an Optional.</p><h4>Forced unwrapped Optional 🔥</h4><pre>var profileImage: UIImage? = nil<br>someImageView.image = profileImage!</pre><h4><strong>Never do this!! 👎🏻</strong></h4><p>What you’ve seen here is an <strong>forced unwrapped Optional.</strong> <br>It is very bad coding and extremely unsafe. Instead of testing against <strong>nil</strong> we say that we are 100% sure that <em>profileImage</em> is <strong>not nil</strong>. If this wouldn’t be the case our app would crash and our users would be <strong>very</strong> unhappy. 😥</p><p>However, there is a safer way of unwrapping a value using the <em>bang operator</em>.</p><pre>if profileImage != nil {<br>    someImageView.image = profileImage!<br>} else {<br>    print(&quot;Can&#39;t get the image.&quot;)<br>}</pre><p>Because we first check if <em>profileImage</em> has a value we can then use the exclamation mark to unwrap it. If the value is <strong>nil</strong> the compiler simply ignores the lines inside the if-block and jump into the else block.</p><h4>Optional Binding (late exit) 👍🏻</h4><p>Instead of using the exclamation mark we can bind the unwrapped value to a temporary constant to use it inside a block:</p><pre>if let profileImage = profileImage {<br>    someImageView.image = profileImage<br>} else {<br>    print(&quot;Can&#39;t get the image.&quot;)<br>}</pre><p><em>By the way: </em>We can name the temporary constant whatever we want to, but it’s common to use the same name as the variable we want to unwrap. Because the compiler reads the positive clause first it has a <strong>late exit</strong>.</p><h4>Guard (early exit) 👍🏻👍🏻</h4><p>The opposite of the late exit is a <strong>guard-statement</strong>. Because it’s else clause is written on top it exits early:</p><pre>guard let profileImage = profileImage else {<br>    print(“Can’t get the image.”)<br>    return<br>}<br>someImageView.image = profileImage</pre><p>Guard statements are much more powerful than the 4 lines we’ve written above, but this is a whole topic of its own.</p><p>With that said I want to thank you for reading until the end of this post. If you like this post, please consider a ❤️ or sharing it with the world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33441c9d9106" width="1" height="1" alt=""><hr><p><a href="https://medium.com/slashkeys-development/how-to-unwrap-optionals-in-swift-33441c9d9106">How to unwrap Optionals in Swift</a> was originally published in <a href="https://medium.com/slashkeys-development">Slashkeys Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>