<?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 Emad Beyrami on Medium]]></title>
        <description><![CDATA[Stories by Emad Beyrami on Medium]]></description>
        <link>https://medium.com/@emad.beyrami?source=rss-c2d2d5a10465------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sBWWdhHw7YUe1CzsRXESGA.jpeg</url>
            <title>Stories by Emad Beyrami on Medium</title>
            <link>https://medium.com/@emad.beyrami?source=rss-c2d2d5a10465------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 16:35:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@emad.beyrami/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[Breaking Up Big SwiftUI Views the Right Way]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://blog.devgenius.io/breaking-up-big-swiftui-views-the-right-way-03babff63d0d?source=rss-c2d2d5a10465------2"><img src="https://cdn-images-1.medium.com/max/800/0*sDzLY46E5nqaTmdA.png" width="800"></a></p><p class="medium-feed-snippet">Why computed properties help readability, what @ViewBuilder actually does, and when a separate View type matters</p><p class="medium-feed-link"><a href="https://blog.devgenius.io/breaking-up-big-swiftui-views-the-right-way-03babff63d0d?source=rss-c2d2d5a10465------2">Continue reading on Dev Genius »</a></p></div>]]></description>
            <link>https://blog.devgenius.io/breaking-up-big-swiftui-views-the-right-way-03babff63d0d?source=rss-c2d2d5a10465------2</link>
            <guid isPermaLink="false">https://medium.com/p/03babff63d0d</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Emad Beyrami]]></dc:creator>
            <pubDate>Wed, 26 Aug 2026 20:46:01 GMT</pubDate>
            <atom:updated>2026-08-26T20:46:01.316Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Supporting Multiple iOS Versions in SwiftUI Without Turning Your Views Into a Mess]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://levelup.gitconnected.com/supporting-multiple-ios-versions-in-swiftui-without-turning-your-views-into-a-mess-cf455f24ed72?source=rss-c2d2d5a10465------2"><img src="https://cdn-images-1.medium.com/max/1536/1*9UZUD47Ra1tJAkspxdPUXg.png" width="1536"></a></p><p class="medium-feed-snippet">One of the best things about SwiftUI is how quickly it evolves. 
Every WWDC introduces new APIs, new modifiers, and small quality-of-life&#x2026;</p><p class="medium-feed-link"><a href="https://levelup.gitconnected.com/supporting-multiple-ios-versions-in-swiftui-without-turning-your-views-into-a-mess-cf455f24ed72?source=rss-c2d2d5a10465------2">Continue reading on Level Up Coding »</a></p></div>]]></description>
            <link>https://levelup.gitconnected.com/supporting-multiple-ios-versions-in-swiftui-without-turning-your-views-into-a-mess-cf455f24ed72?source=rss-c2d2d5a10465------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf455f24ed72</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Emad Beyrami]]></dc:creator>
            <pubDate>Mon, 03 Aug 2026 15:28:37 GMT</pubDate>
            <atom:updated>2026-08-03T15:28:37.351Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Apple Foundation Models introduction]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://blog.devgenius.io/apple-foundation-models-introduction-239d7d8acb02?source=rss-c2d2d5a10465------2"><img src="https://cdn-images-1.medium.com/max/1536/1*B8EGV2o7nIxtrqFBdOKEKA.png" width="1536"></a></p><p class="medium-feed-snippet">An overview and the basics of how it works</p><p class="medium-feed-link"><a href="https://blog.devgenius.io/apple-foundation-models-introduction-239d7d8acb02?source=rss-c2d2d5a10465------2">Continue reading on Dev Genius »</a></p></div>]]></description>
            <link>https://blog.devgenius.io/apple-foundation-models-introduction-239d7d8acb02?source=rss-c2d2d5a10465------2</link>
            <guid isPermaLink="false">https://medium.com/p/239d7d8acb02</guid>
            <dc:creator><![CDATA[Emad Beyrami]]></dc:creator>
            <pubDate>Wed, 27 Aug 2025 14:33:21 GMT</pubDate>
            <atom:updated>2025-08-27T14:33:21.973Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Build a SwiftUI PreviewProvider for UIKit Views]]></title>
            <link>https://medium.com/better-programming/swiftui-preview-provider-for-uikit-3dd089d77915?source=rss-c2d2d5a10465------2</link>
            <guid isPermaLink="false">https://medium.com/p/3dd089d77915</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Emad Beyrami]]></dc:creator>
            <pubDate>Tue, 04 Jan 2022 23:44:56 GMT</pubDate>
            <atom:updated>2022-12-26T10:52:36.051Z</atom:updated>
            <content:encoded><![CDATA[<h4>A simple way to see your UIKit ViewController changes instantly — live and on-demand</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QLUjIXB7hVrCxcPoSXa8Vw.png" /><figcaption>All images by author</figcaption></figure><p>Have you ever tried the SwiftUI? Haven’t you found it so delightful and easy to work with?</p><p>However, in UIKit views, if you are prototyping a design in your codebase, you have to recompile and build your project every time to see the results in the simulator. But in SwiftUI it’s so pleasant to view changes on-demand without rebuilding.</p><p>What if we can do that something similar to it for our UIKit Components? Like previewing or hot reloading the UIKit changes immediately without the time-consuming build and compile process.</p><p>Essentially, we’re looking to create a live preview system for our UIKit views using SwiftUI.</p><p>There are many ways to make this process easier such as simple annotations like @IBDesignable<strong>, </strong>@IBInspectable<strong> </strong>and etc.</p><p>But if you have experience using these sometimes it gets buggy and causes some compile errors for rational reasons and sometimes it’s not the best approach.</p><p>So in this article, you will learn a new and way simpler way to see your changes instantly. if you used SwiftUI you already know it but we add a little trick to it so it will work with UIKit.</p><h3>SwiftUI: PreviewProvider</h3><p><a href="https://developer.apple.com/documentation/swiftui/previewprovider">PreviewProvider</a> is a protocol type that produces view previews in Xcode. It contains an associated type called Previews which is of type View. View is a SwiftUI view that we’ll return for the PreviewProvider to display — we’ll see this later.</p><p>After creating an object which is conforming to this protocol, we’ll pass the view we want to see in our preview. It’ll automatically pop up a split view like the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xOVl5URWTfEPpiCn2ocNgQ.png" /></figure><p>If the preview doesn’t load, worry not: simply use the below keyboard shortcut to see the reset the live preview:</p><pre><strong>⌘ + ⌥ + Return (Command + option + Return)</strong></pre><p>Note: Make sure to click on the resume button that appears in the upright corner of the preview content if you won’t see that it means it is working and showing you the live content.</p><h3>UIKit: PreviewProvider</h3><p>So now that we know about the PreviewProvider and how it works in SwiftUI, how can we achieve this in UIKit?</p><p>The answer is simple: We have to convert our UIKit codebase into something that SwiftUI understands and use the SwiftUI PreviewProvider to see the live simulation of the content. Any guesses how?</p><h4>How to convert UIKit content to SwiftUI Content?</h4><p>It is way easier than you think. Don’t make it complicated. All we need is the popular UIViewControllerRepresentable protocol.</p><p>UIViewControllerRepresentable acts as a bridge to help convert the UIViewController to SwiftUI view. Have you guessed what are we planning to do yet?</p><h4>Implementation</h4><p>Now that we know about UIViewControllerRepresentable<strong> </strong>and<strong> </strong>PreviewProvider<strong> </strong>in SwiftUI, Let’s get our hands dirty and use them in a practical way.</p><h4>UIKit Controller</h4><p>Let’s create a simple UIKit controller (UIViewController) which contains some UI modifications:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b642c65a3bb6491660d55ef9463cf180/href">https://medium.com/media/b642c65a3bb6491660d55ef9463cf180/href</a></iframe><p>If we run this ViewController you will see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-aav-Jh0JOBWazsmDMZPGg.png" /></figure><p>Now let&#39;s create a SwiftUI Preview. Any changes we’ll make in the UIKit UI could be simply displayed in real-time and we won’t have to build and compile like earlier.</p><h4>Convert this UIViewController to SwiftUI Controller</h4><p>We simply make an object from our controller which is conforming to UIViewControllerRepresentable to make it readable for SwiftUI.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5787c0b24877b63d50fd2195020a7c6/href">https://medium.com/media/c5787c0b24877b63d50fd2195020a7c6/href</a></iframe><p>In the above code:</p><ul><li>canImport(SwiftUI) is used to ensure it will compile only for the iOS versions which support SwiftUI .</li><li>DEBUG makes sure it is running in our debug environment only.</li></ul><p>Inside the MakeUIViewController(context: Context)<strong> </strong>function, you should simply instantiate the Controller you want to see in previews.<br>Here I just instantiated my Main Storyboard.</p><h4>Preview our UIViewController using PreviewProvider</h4><p>Now that we have the UIViewController and have already converted it to SwiftUI Controller we just have to add a few lines of code for our PreviewProvider.</p><p>Add the following lines of code before the #endif:</p><pre>struct ViewController_Preview: PreviewProvider {<br>    static var previews: some View {<br>         ViewControllerRepresentable()    <br>    }<br>}</pre><p>The full code should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ee69d5646e7bdc96a6c9b2ffd5601c7/href">https://medium.com/media/6ee69d5646e7bdc96a6c9b2ffd5601c7/href</a></iframe><p>Now that we have the full codebase, you can see the live preview<strong> </strong>of the UIKit UIViewController<strong> </strong>on-demand. Try modifying the UI slightly and notice the instant results. Say goodbye to the time-consuming building process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NMi7aptErn1IqLV9iBUQow.png" /></figure><p>That’s all for now. Thanks for reading. You can check the full source code below:</p><p><a href="https://github.com/EmadBeyrami/UIKitPreviews">GitHub - EmadBeyrami/UIKitPreviews</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3dd089d77915" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/swiftui-preview-provider-for-uikit-3dd089d77915">Build a SwiftUI PreviewProvider for UIKit 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[Keyed Object in Codable]]></title>
            <link>https://medium.com/@emad.beyrami/keyed-object-in-codable-7e5e81be9fa7?source=rss-c2d2d5a10465------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e5e81be9fa7</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[codable]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[json-api]]></category>
            <dc:creator><![CDATA[Emad Beyrami]]></dc:creator>
            <pubDate>Sun, 26 Sep 2021 11:19:06 GMT</pubDate>
            <atom:updated>2022-08-02T09:42:58.790Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*1d-KOwYaq9khZ2Tq2U-j-w.jpeg" /></figure><h3>Introduction</h3><p>Lately, I was trying to work with Wikipedia APIs for a simple project which is available on <a href="https://github.com/EmadBeyrami/NearbyWiki"><strong>my Github</strong></a>, I’ve found out there are some APIs using Keyed Object response. <br>So in this article, we learn how “Codable” works and how to decode Keyed Object Response.<br>For this tutorial you need to know some basics of using codable and iOS Programming.<br>This is not a complete toturial of codable, you need to know about it.</p><h4>What is a Keyed Object Response?</h4><p>what do I mean by Keyed Object, lets start with this example Response.<br>Check out <a href="https://en.wikipedia.org/w/api.php?action=query&amp;prop=info%7Cdescription%7Cimages&amp;pageids=18806750&amp;format=jsonfm">THIS LINK</a> or the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d7MI5x9blW-guxbjxnVn2Q.png" /></figure><p>To explain the Response, we send a query parameter to the server which in this case is an ID for an article and the ID is 18806750. This ID will become the key of an object in the response which means this Key will change with every request. but it doesn’t matter if we know what it is.<br>so first let explain how codable works.</p><h4>What is Codable?</h4><p>Codable is a simple way to encode and decode or serialize and deserialize and parse JSON data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1anKsvbwxtXnAmX-zXAkLA.png" /></figure><p>As can be seen, Codable is a “type alias” of whatever conforms to “Decodable” and “Encodable” Protocols. in this case we focus on the “Decodable” part.<br>when there is a JSON, the way to parse its data is to Decode its data Key by Key which you need to know the name of each key.<br>so there is a protocol called “CodingKeys” which is associated with “Codable”.</p><h4>What is CodingKey?</h4><p>This protocol is responsible to represent the KeyName of each Key in JSON.<br>This is how “CodingKey” is defined in swift.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AupYhxDOViOOPrr2w-WaSQ.png" /></figure><h4>How to simply Decode using CodingKey?</h4><p>the usual way to decode data is to create an enum to return a string value of Key Name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBf1rCiTwsZNsxUXbmWnhQ.png" /></figure><p>This is how we usually set CodingKeys right?</p><h4>Keyed Object Decodable</h4><p>So as we understand we need to know the “<strong>Key Name</strong>” to <strong>decode</strong> properly but in <strong>Keyed</strong> <strong>Object responses </strong>the “<strong>Key Name”</strong> is constantly <strong>changing</strong> in every response we get. so what should we do now? here is how to parse data of an unknown and changing key.</p><p>First of all, we need to define the type of the object as a dictionary:</p><blockquote>let response: [String: PageDetailModel]?</blockquote><p>We do this because we know the object we want to parse has a <strong>String type </strong>“<strong>key name</strong>” and its value will be a type of the <strong>PageDetailModel. </strong>it can be “<strong>Any</strong>” or any other object you know it can be.</p><p>So we did the first step what to do next?<br>in this use case we won’t use <strong>enum</strong> <strong>CodingKeys</strong> because enum is for <strong>static</strong> values we cannot change the value in advance. as we learned “<strong>CodingKey” </strong>is a Protocol and we can use it however we like as long as we conform to it. in this case, we will know the name of the key on the fly when we got the response. so we create a <strong>Struct</strong> conforming to the coding key protocol like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yXa8LQ8jPMW-QL0ssyXwSQ.png" /></figure><p>so what we do here is we created a struct conforming to CodingKey and we initialize the string value to return it on demand. this way we can make our codingKey dynamic and initialize it with whatever we need to. Isn’t it beautiful?</p><h4>Final step: Custom Decoding</h4><p>So we have our ingredient what should we do to cook the meal?<br>here it comes the final step, the final step is to customize our decoding way every codable needs the structure to decode. the usual decoder looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YiAir7pvoV1v8q7ZkfZQuQ.png" /></figure><p>As can be seen the common way of decoding is like this but in our case it is different so we need to define how it should be decode and how to decode by our custom key. so here it is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MT05ueMvH-Bid1phEWljug.png" /></figure><p>it is as simple as that. hope you enjoyed it.</p><p>If you found this helpful and useful please clap. Don’t forget you can clap up to 50 times :). so motivate me to create more content. <br>Follow me <strong>here</strong> and on <a href="https://github.com/EmadBeyrami/">G<strong>ithub</strong></a> and <a href="https://www.instagram.com/emad.cs"><strong>Instagram</strong></a>. Thank you!</p><p><a href="https://github.com/EmadBeyrami/">EmadBeyrami - Overview</a></p><h3>Buy me a coffee ☕️:</h3><ul><li><a href="https://www.paypal.com/donate/?hosted_button_id=FRY432D75E4Q2">Donate to Emad Bayramy</a></li><li><a href="https://nowpayments.io/donation/emad">NowPayments</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e5e81be9fa7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Protocol-Oriented Programming vs. Object-Oriented Programming in Swift]]></title>
            <link>https://medium.com/better-programming/difference-between-protocol-oriented-programming-pop-and-object-oriented-programming-oop-in-swift-2dc3048b4fd?source=rss-c2d2d5a10465------2</link>
            <guid isPermaLink="false">https://medium.com/p/2dc3048b4fd</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[developer]]></category>
            <dc:creator><![CDATA[Emad Beyrami]]></dc:creator>
            <pubDate>Fri, 28 Feb 2020 13:09:14 GMT</pubDate>
            <atom:updated>2022-08-02T09:43:26.417Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Differences Between Protocol Oriented Programming (POP) and Object-Oriented Programming(OOP) in Swift</h3><h4>Why we need protocols and when should we use them</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HA5txJWZViUfPlD2lphLMw.jpeg" /><figcaption>Object-Oriented vs. Protocol-Oriented Programming</figcaption></figure><h3>Introduction</h3><p>I’ve had many interviews, with startups and large companies, and they all asked me questions like this:</p><ul><li>What are the differences between protocols and classes?</li><li>Why not use superclasses instead of protocols?</li></ul><p>This article will give you the answer to these type of questions and may introduce you to a new aspect of Swift programming.</p><p>After reading this you will understand why protocols are made, when we can we use them, why we should we choose them over the superclass, and what the pros and cons are.</p><p>Let’s stop talking and start doing!</p><h3>Inheritance Problems</h3><p>When coming from an Object-Oriented Programming language, inheritance is often used to share code between multiple classes. But that solution is not always the best and has some issues.</p><p>Say you have an app with a lot of UIViewController classes that share the same behaviour —they all have a profile picture, for example. Of course, you don’t want to reimplement the profile picture logic — setting up the leftBarButtonItem, opening and closing the edit profile ViewController when the button is tapped, etc — in every view controllers in your app.</p><p>The solution is easy. Just create a MainViewController, subclass of UIViewController that implement all those behaviours and then make all your ViewControllers inherit from that MainViewController, instead of inheriting from UIViewController directly. That way, they all inherit those methods and behave the same way — there’s no need to reimplement everything every time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4fa363d1bcea6e9166a5eed8843596f/href">https://medium.com/media/f4fa363d1bcea6e9166a5eed8843596f/href</a></iframe><p>But later, during the development process, you realize that you need an UITableViewController or UICollectionViewControlle. Unfortunately, you can’t use the MainViewController because it inherits UIViewController, notUICollectionViewController or UITableViewController.</p><p>How can we make a MainTableViewController that implements the same things as MainViewController but inherits from UITableViewController instead of UIViewController? That would be a lot of code duplication, right?</p><h3>Here Comes Composition</h3><p>Of course, the typical and easy answer is composition.</p><p>This means that instead of making use of inheritance,UIViewController contains or is composed of inner classes that provide the behaviour.</p><p>In our case, we could imagine a ProfileManager class that provides all the needed methods to set up the profile picture image and interact with it. The various UIViewControllers will then have a <em>property</em> holding a ProfileManager and can use it to interact with the profile bar button:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2498d073c933c49688fc6bcdd234813/href">https://medium.com/media/b2498d073c933c49688fc6bcdd234813/href</a></iframe><p>You can see how that could get complicated. You need to explicitly reference the intermediate object ProfileManager each time. In a way, this is also duplication and it may take you longer to implement.</p><h3>Multiple Inheritances</h3><p>Another problem with inheritance is the fact that many object-oriented languages don’t allow multiple inheritances — for many good reasons, especially <a href="https://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem">the diamond problem</a>.</p><p>This means that a class can’t inherit multiple superclasses.</p><p>Let’s say you’re God and you want to implement model classes representing living creatures. You have Bird, Fly , Human, Monkey — how do they relate to each other? Some can walk, some can fly, some can do both; some can talk and some can’t, some are animals and some aren’t.</p><p>The class Mockingbird and the class Mosquito can both fly, so we can imagine aFlyer superclass which provides the implementation of the func fly() method. But Mockingbird and Eagle are both birds, so we can also imagine a Birds superclass, while Mosquito and Bees will be subclasses of the Flies class. So Mockinbird inherits from both Flyer and birds? That’s not possible in Swift (and a lot of OOP languages).</p><p>Should we choose one over the other? But if we make anIcarusor let’s say Superman subclass of Human — what about the implementation of the func fly() method? We can’t implement it in Human because not every human can fly, but Supermanand Icarus will need that method too, and we don’t want to duplicate it.</p><p>So, we could use composition there, like make class Icarus be <em>composed</em> of a var flyingOption: Flyer property. But having to write Icarus.flyingOption.fly() instead of just Icarus.fly() is not pretty.</p><h3>Mixins and Traits to the Rescue</h3><p>Here’s where the concept of mixins and traits comes into play.</p><ul><li>With inheritance, you define what your classes are. For example every Dog is an Animal.</li><li>With traits, you define what classes <em>can do</em>. For example, every Animal can eat() as can humans, birds, and all other creatures.</li></ul><p><em>While inheritance lets you describe what an object is, traits let you describe what an object can do.</em></p><p><em>Inheritance is your object identity but traits will define what your object is capable of doing.</em></p><p>Best of all, a class can adopt multiple Traits, as it can do multiple things, while it can only be one thing (inherit only one superclass). That means we have one identity, human, but we have multiple abilities: walking, talking, eating, even flying sometimes. But some other creatures are able to do these too, so they’re not unique and specific for human beings.</p><p>So how can we do this in Swift?</p><h3>Protocols are the Answer</h3><p>Protocols can have a default implementation In Swift 2.0 when you define a protocol, you can give default implementations to some or all methods of that protocol, using an extension of that protocol. Here’s what it looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17ceb8b35e41323f9b2cca104a1edaf1/href">https://medium.com/media/17ceb8b35e41323f9b2cca104a1edaf1/href</a></iframe><p>When you create a class or struct that conforms to that Flyer protocol, it gets an implementation of the fly() method for free!</p><p>That’s still a <em>default implementation — y</em>ou’re free to redefine that method if you need to, but if you don’t you’ll still have the default one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72067229ac1a412a858fd528eb5a3881/href">https://medium.com/media/72067229ac1a412a858fd528eb5a3881/href</a></iframe><p>That feature of protocols with default implementation is great for many things — including bringing the “traits” concept to Swift.</p><h3>One Identity, Multiple Abilities</h3><p>The great thing about traits is that they don’t depend on the identity of the object you apply them to. They don’t care what the class is and what it inherits from, they just define some functions on that class.</p><p>That solves our problem of Icarus being both a human and able to fly while the Mockingbird is able to fly and is a bird.</p><p><em>What you are doesn’t define what you can do.</em></p><p>Let’s implement our model classes by taking advantage of traits now. First, let’s define the various traits:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bfec7ddd0cca3ae6e83d6baccd7f709/href">https://medium.com/media/1bfec7ddd0cca3ae6e83d6baccd7f709/href</a></iframe><p>Then let’s give them some default implementations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fb616fa5de72918a9ba9ba8552abab9/href">https://medium.com/media/2fb616fa5de72918a9ba9ba8552abab9/href</a></iframe><p>At this point, we’ll still use inheritance to define the identities of our creatures (what they are), so let’s have some parent classes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6822365f3d088ce59165a582dc55628a/href">https://medium.com/media/6822365f3d088ce59165a582dc55628a/href</a></iframe><p>Now we can define our characters by both their identity (via inheritance) and abilities (traits/protocol conformance):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42be02381347e5fb52816d4304d25c7b/href">https://medium.com/media/42be02381347e5fb52816d4304d25c7b/href</a></iframe><p>Now both Icarus and IronMan and Bee use the same implementation of fly() even if they inherit from a different superclass (Insect for one, Human for the other), and both Spider and Icarus know how to Eat even if one is human and the other is an insect:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d5164f24d8b360c9664ba707edf758d/href">https://medium.com/media/9d5164f24d8b360c9664ba707edf758d/href</a></iframe><h3>An Adventure in Space and Time</h3><p>Now let’s introduce a new space travel ability/trait:</p><pre><strong>protocol</strong> SpaceTraveler {<br>     <strong>func</strong> travelTo(location: String)<br>}</pre><p>And give it a default implementation:</p><pre><strong>extension</strong> SpaceTraveler {<br>    <strong>func</strong> travelTo(location: String) {<br>         print(&quot;Let&#39;s go to \(location)!&quot;)<br>    }<br>}</pre><p>We can then use Swift’s extensions to add conformance to a protocol to an existing class, so let’s add those abilities to the creatures we already defined:</p><pre><strong>extension</strong> Superman: SpaceTraveler {}</pre><p>Yes, that’s all it takes to add this ability/trait to the existing classes! Just like that, they can now travelTo() any place!</p><pre>clark.travelTo(location: &quot;Trenzalore&quot;) // prints &quot;Let&#39;s go to Trenzalore!&quot;</pre><h3>Let’s Invite More People to the Party!</h3><p>Now let’s introduce some more people to the mix, this time I want to use more Sci-fi Creatures to make it more unrealistic and irrational and to make more impossible ways to create models:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f10230a6e9b581cf6c77e3f8859734d4/href">https://medium.com/media/f10230a6e9b581cf6c77e3f8859734d4/href</a></iframe><p>We have a problem here. Laika is not a human, neither is Chewie, and Spock is half human and half Vulcan, so those definitions are quite wrong.</p><p>Do you see the problem here? We’ve taken it for granted that Human and Alien are identities — and we’ve been bitten by inheritance again. Some classes were forced to be of a certain type, or inherit from some parent class, whereas in fact, that’s not always the reality — especially in sci-fi.</p><p>That’s also why using protocols in Swift and protocols default implementations can help to remove those constraints imposed on your classes by inheritance.</p><p>If Human and Alien were protocols instead of classes, we’d have a lot of benefits:</p><ul><li>We could define a MilleniumFalconPilot type without forcing it to be a Human, thus allowing Chewie to drive it.</li><li>We could define Laïka as an Astronaut even if she’s not Human.</li><li>We could define Spock as both Human and Alien.</li><li>We could even totally get rid of inheritance in our case and define our types as structs instead of classes. A struct doesn’t support inheritance, but can still conform to as many protocols as you want.</li></ul><h3>Protocols Everywhere!</h3><p>So, one solution to this is to make everything a protocol and get rid of inheritance. After all, we don’t care <em>what</em> our creatures are, what defines heroes and creatures are the <em>abilities</em> they have!</p><p>I’ve included a Swift Playground that you can download <a href="https://github.com/EmadBeyrami/OOP-Vs-POP">here</a> that contains the code shown in this article. It also demonstrates another playground as a solution with everything made of protocols and structs, with no inheritance at all. Take a look!</p><p>Of course, that doesn’t mean that you have to get rid of inheritance at all costs. Inheritance is still useful and can still make sense. It still feels logical that a UILabel is a <em>subclass</em> of UIView. But this gives you a taste of what mixins and protocols with default implementations can offer.</p><h3>Conclusion</h3><p>Practising Swift, you’ll realize that it’s really a protocols-oriented language and that using a protocol is more common and more powerful in Swift that it was in Objective-C. After all, protocols like Equatable, CustomStringConvertible and any protocol in -able in the Swift standard library can actually be seen as Mixins!</p><p>Even many built-in Swift APIs are use protocols such as UITableViewDelegate, UITableViewDataSource, and many others.</p><p>With Swift protocols and protocols default implementations, you can implement mixins and traits and make your code much more flexible.</p><p>The mixins and traits approach allows you to describe types by what they can do rather than what they are, and more importantly, to opt-in capabilities into your types. It’s like doing your shopping and picking the capabilities you want for your type, whatever the class they inherit, if any.</p><p>Going back to the first example — you can create a protocol ProfilePictureManager with a default implementation, then simply make your view controllers (whether they are UIViewController, UITableViewController or whatnot) conform to that protocol. It will then automatically gain those abilities and features from ProfilePictureManager for free, without worrying about the parent class of the UIViewController!</p><p>Thank you for reading my article. I hope you enjoyed it. There are more amazing things we can do using protocols and protocol extensions but this article is already long enough.</p><h3>Buy me a coffee ☕️:</h3><ul><li><a href="https://www.paypal.com/donate/?hosted_button_id=FRY432D75E4Q2">Donate to Emad Bayramy</a></li><li><a href="https://nowpayments.io/donation/emad">NowPayments</a></li></ul><p>Thank you for your support in advance!</p><h3>References and Resources</h3><ul><li><a href="https://github.com/EmadBeyrami/OOP-Vs-POP">https://github.com/EmadBeyrami/OOP-Vs-POP</a></li><li><a href="https://www.appcoda.com/pop-vs-oop/">https://www.appcoda.com/pop-vs-oop/</a></li><li><a href="https://tsh.io/blog/protocol-oriented-programming-swift/">https://tsh.io/blog/protocol-oriented-programming-swift/</a></li><li><a href="https://alisoftware.github.io/swift/protocol/2015/11/08/mixins-over-inheritance/#fn:diff">https://alisoftware.github.io/swift/protocol/2015/11/08/mixins-over-inheritance/#fn:diff</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2dc3048b4fd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/difference-between-protocol-oriented-programming-pop-and-object-oriented-programming-oop-in-swift-2dc3048b4fd">Protocol-Oriented Programming vs. Object-Oriented Programming in Swift</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>
    </channel>
</rss>