<?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 Kiarash Vosough on Medium]]></title>
        <description><![CDATA[Stories by Kiarash Vosough on Medium]]></description>
        <link>https://medium.com/@vosough.k?source=rss-90202252b256------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YgK3reDEj8h3PyXzndy6OA.jpeg</url>
            <title>Stories by Kiarash Vosough on Medium</title>
            <link>https://medium.com/@vosough.k?source=rss-90202252b256------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:33:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vosough.k/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[Map Models Made Easy]]></title>
            <link>https://medium.com/@vosough.k/map-models-made-easy-daaa00150f08?source=rss-90202252b256------2</link>
            <guid isPermaLink="false">https://medium.com/p/daaa00150f08</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Kiarash Vosough]]></dc:creator>
            <pubDate>Sun, 17 Nov 2024 18:27:03 GMT</pubDate>
            <atom:updated>2024-11-17T18:27:03.099Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we’ll look at a simplified approach to model mapping in Swift, making it easier to map data across architecture layers without unnecessary complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Ey68uHrKtAxkP0_LXKqSHw.png" /></figure><h3>Introduction</h3><p>In software development, it’s common to encounter situations where you need to map one model to another, especially when transferring data between different layers of your application architecture. Often, this process involves additional parameters that must be filled in the target model or long lines of code to ensure proper transformation. Managing these mappings efficiently is essential for clean and maintainable code.</p><pre>struct Employee {<br>    let id: Int<br>    let name: String<br>    let department: String<br>}<br><br>struct FullTimeEmployeeViewModel {<br>    let someService: Service <br>    let employee: Employee<br>}</pre><p>Imagine Presentation layer need <strong>FullTimeEmployeeViewModel</strong> and on usecase layer we have fetch to <strong>Employee</strong>. Now we need to Map UseCase Model to presentation view-model.</p><p>Normally we can do this mapping inline inside a presentation component like a parent view-model like this:</p><pre>list.map { employee in<br>   FullTimeEmployeeViewModel(<br>       someService: di.someService,<br>        employee: employee<br>    )<br>}</pre><p>However, the process isn’t always straightforward. Sometimes, models require additional parameters or static values for transformation. You might find yourself writing long, repetitive lines of code to accommodate this. Writing code for these transformations repeatedly can make your codebase harder to maintain and cluttered.</p><h3>Solution</h3><p>Leveraging protocol is a good solution to craft a stable solution, so Here is the mapper protocol:</p><pre>protocol Mapper {<br><br>    associatedtype From<br>    associatedtype To<br>    <br>    func map(from entity: From) -&gt; To<br>}</pre><p>This protocol enables us to encapsulate the mapping procedure into new structure:</p><pre>struct FullTimeEmployeeMapper: Mapper {<br>    <br>    func map(from entity: Employee) -&gt; FullTimeEmployeeViewModel {<br>         FullTimeEmployeeViewModel(someService: ??, employee: entity)<br>    }<br>}</pre><p>When a ViewModel requires an additional service, what’s the best approach to handle it? Should we pass the service using a generic tuple parameter, or is it better to create a dedicated Data Transfer Object (DTO) for this purpose? Ideally, we aim to minimize boilerplate code, but finding the right balance is key to maintaining clean architecture and flexibility.</p><p>I present you the third generic parameter in protocol <strong>Context</strong> which is default to<strong> Void</strong> to avoid declare it when it is not required.</p><pre>protocol Mapper {<br><br>    associatedtype From<br>    associatedtype To<br>    associatedtype Context = Void<br><br>    func map(from entity: From, context: Context) -&gt; To<br>}</pre><p>Using context, you can create a container within the mapper that passes necessary parameters alongside the source entity. To maintain a functional programming approach, this container is used as a parameter within the map method rather than being injected directly into the structure. This keeps the mapping process clean, modular, and aligned with functional programming principles.</p><blockquote>The downside of passing Context to the map method is that it limits flexibility. If you treat mappers as protocols (which isn’t always ideal since mappers are typically used in place rather than as injected services), you lose the ability to provide different contexts for different use cases. But You can adapt the mapper protocol to better align with your requirements.</blockquote><pre>struct FullTimeEmployeeMapper: Mapper {<br>    <br>    struct Context {<br>         let someService: SomeService<br>    }<br>    func map(from entity: Employee, context: Context) -&gt; FullTimeEmployeeViewModel {<br>       FullTimeEmployeeViewModel(<br>            someService: context.someService, <br>            employee: entity<br>        )<br>    }<br>}</pre><p>Now that we have the complete idea laid out, let’s refine it further. Here are some improvements:</p><ul><li>Define all associated types as primary associated types. This enables easier passing mapper as protocol and not depending on implementation.</li><li>Add a default implementation for the map method where the Context is Void, so there’s no need to implement Void each time.</li><li>Make the map method <strong><em>throwable</em></strong> to handle cases where something could go wrong during the mapping process.</li></ul><p>These adjustments will enhance both the usability and robustness of the mapping process.</p><pre>protocol Mapper&lt;From, To, Context&gt; {<br><br>    associatedtype From<br>    associatedtype To<br>    associatedtype Context = Void<br><br>    func map(from entity: From, context: Context) throws -&gt; To<br>}<br><br>extension Mapper where Context == Void {<br>    func map(from entity: From) throws -&gt; To {<br>         try map(from: entity, context: ())<br>    }<br>}</pre><h3>Conclusion</h3><p>Using a mapping protocol like <strong><em>Mapper</em></strong> provides a clean, modular approach to transforming data models in Swift, especially within layered architectures like MVVM or Clean Architecture. This structure brings several advantages:</p><p>1. <strong>Separation of Concerns</strong>: The <strong><em>Mapper</em></strong> protocol abstracts the transformation logic, isolating it from the core business logic. This keeps each layer of your architecture focused on its specific role, improving code readability and maintainability.</p><p>2. <strong>Reusability and Scalability</strong>: With a generic <strong><em>Mapper </em></strong>protocol, you can easily create additional mappers to handle various model transformations without duplicating code. This setup is flexible enough to support diverse model transformations as the app scales, especially if multiple layers or modules require similar transformations.</p><p>3. <strong>Improved Readability</strong>: By organizing mapping logic within dedicated mappers, the overall readability of your code improves. Rather than embedding transformation details within different parts of the codebase, they’re centralized, making it easy for future developers to understand and maintain.</p><p>In summary, implementing a mapping protocol structure enhances the modularity, flexibility, and maintainability of your codebase, allowing you to handle complex data transformations between architecture layers more effectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=daaa00150f08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tired Of Objc Method Swizzling? Check Out Swifty Alternative.]]></title>
            <link>https://medium.com/divar-mobile-engineering/tired-of-objc-method-swizzling-check-out-swifty-alternative-c6606313a883?source=rss-90202252b256------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6606313a883</guid>
            <category><![CDATA[objective-c]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Kiarash Vosough]]></dc:creator>
            <pubDate>Sat, 17 Dec 2022 10:05:41 GMT</pubDate>
            <atom:updated>2022-12-17T10:05:41.915Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will demonstrate an alternative to Objc method swizzling, with extension even for swift’s structs and enums.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*Cqn6O4X0SnQgAMbe66ts_A.png" /></figure><h3>Recall Old-School Objc Method Swizzling</h3><p>If you are an iOS Developer, you have inevitably used Method Swizzling so-far. Although it is not a safe API, a large group of libraries have used it for some reasons. Let&#39;s see the old-school way of method swizzling.</p><pre>class SomeThing: NSObject {<br>  @objc dynamic<br>  func original(x: Int) {<br>    print(&quot;original called&quot;)<br>  }<br>}<br><br>extension SomeThing {<br>  @objc dynamic<br>  func replacement(x: Int) {<br>    print(&quot;replacement called&quot;)<br>  }<br>}<br><br>func beforeAfter() {<br>  let thing = SomeThing()<br>  thing.original(x: 10) // calls original(x:)<br><br>  // extract selector of the original method<br>  let origMethod = #selector(SomeThing.original(x:))<br><br>   // extract selector of the replacement method<br>  let replacementMethod = #selector(SomeThing.replacement(x:))<br><br>  // get the method from the selector and object<br>  let method: Method? = class_getInstanceMethod(SomeThing.self, origMethod)<br><br>  // get the replacement method from the selector and object<br>  let swizzleMethod: Method? = class_getInstanceMethod(SomeThing.self, replacementMethod)<br><br>  // get the implementation of the replacement method<br>  let swizzleImpl = method_getImplementation(swizzleMethod!)<br><br>  // change implementation<br>  method_setImplementation(method!, swizzleImpl);<br><br>  thing.original(x: 10) // calls replacement(x:)<br>}</pre><p>Writing such a long code to change implementation with Objc runtime API is not so convenient.</p><h4>About the Downsides Of This Method:</h4><ul><li>It’s very hard to use, there is zero type safety.</li><li>If you forget to mark the entity as dynamic the swizzling won&#39;t take effect, because Swift code won’t necessarily call through the Objective-C entry point.</li><li>It only works for @objc entities, which limits it to methods of classes that can be expressed in the subset that’s exposed to Objective-C.</li></ul><h3>Swifty Method To Swizzling</h3><p>This Method extends a similar functionality to all Swift classes, structs, and enums. To allow the runtime to replace a method’s, property’s, initializer’s, or subscript’s implementation mark it with dynamic.</p><blockquote>In my experience, do not use the playground to test these codes as it throws errors and the code won’t be compiled. Create a macOS-Terminal project for simplicity.</blockquote><pre>struct SomeThing {<br>    dynamic var someNumber: Int {<br>        return 10<br>    }<br><br>    let c: Int<br>    <br>    dynamic init(num: Int) {<br>        c = num<br>    }<br>}</pre><p>To replace the implementation write a method of the same type inside the same scope and mark the method with the @dynamicReplacement(for:) attribute specifying the original method.</p><pre>extension SomeThing {<br>    @_dynamicReplacement(for: init(num:))<br>    init(number: Int) {<br>        self.c = number + 1<br>    }<br><br>    @_dynamicReplacement(for: someNumber())<br>    var newNumber: Int {<br>        return 42<br>    }<br>}</pre><p>The Swift runtime will perform the replacement on the application start/loading of the shared library containing the replacement. That the replacement happens at the program start (or loading a shared library), instead of at an arbitrary point in time.</p><h3><strong>Tips To Use</strong></h3><h4><strong>First:</strong></h4><p>The @dynamicReplacement(for:) attributes indicate which dynamic declaration is replaced by the new declaration. This declaration must have the <strong><em>same type</em></strong> and be on an <strong><em>extension of the owning type</em></strong> or at <strong><em>module scope</em></strong> for dynamic non-member declarations.</p><pre>// Module A<br>extension Set where Element: SomeProtocol {<br>  dynamic func foo() { }<br>  dynamic func bar() { }<br>}<br><br>// Module B<br>extension Set {<br>  @_dynamicReplacement(for: foo())<br>  dynamic func myFoo() { }  // ERROR: signature of MyFoo doesn&#39;t match the signature of foo<br>}<br><br>// Module B<br>extension Set where Element: SomeProtocol {<br>  @_dynamicReplacement(for: bar())<br>  dynamic func myBar() { }   // okay: signatures match<br>}</pre><p>You might wonder why Module B has an error, that’s because the constraint that <strong><em>foo()</em></strong> and <strong><em>bar()</em></strong> were declared for, is not met. This ensures that the code has still some boundaries and we have restrictions for swizzling. As Comparison, This couldn’t be achieved with old Objc APIs like the below:</p><pre>let original = #selector(Set&lt;Element&gt;.add()) where Element: SomeProtocol<br>let replacement = #selector(Set&lt;Element&gt;.add()) where Element: SomeProtocol<br>let success = swift_method_exchange(original, replacement)</pre><h4>Second:</h4><p>A call to the original function from within its replacement will call the original function definition, not recurse to itself. For example:</p><pre>// Module A<br>dynamic func call() -&gt; Int {<br>  return 20<br>}<br><br>// Module B<br>@dynamicReplacement(for: theAnswer())<br>dynamic func mycall() {<br>  return call() + 22<br>}</pre><h3>UseCases</h3><ol><li>Add a new implementation and retain the original method to call inside the replaced method.</li><li>Can be used for testing and mocking.</li><li>Introspecting frameworks and changing their behaviors.</li></ol><p>As Swift evolves, we should evolve too, moving from old unsafe APIs to the Swifty Alternatives.🔥</p><p>Hope this was helpful and extends your swift knowledge. Have a great weekend🥳🥳🥳🥳🥳🥳🥳</p><p>Check My <a href="https://www.linkedin.com/in/kiarashvosough?lipi=urn%3Ali%3Apage%3Ad_flagship3_feed%3B1T2JzV3qT8u29cexmuG7NA%3D%3D"><strong>Linkedin</strong></a> for new updates and swift stories.🫡</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6606313a883" width="1" height="1" alt=""><hr><p><a href="https://medium.com/divar-mobile-engineering/tired-of-objc-method-swizzling-check-out-swifty-alternative-c6606313a883">Tired Of Objc Method Swizzling? Check Out Swifty Alternative.</a> was originally published in <a href="https://medium.com/divar-mobile-engineering">Divar Mobile Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distinguish Protocols Requirement Which Has Same Signature]]></title>
            <link>https://medium.com/@vosough.k/distinguish-protocols-requirement-which-has-same-signature-570ecbb1eefc?source=rss-90202252b256------2</link>
            <guid isPermaLink="false">https://medium.com/p/570ecbb1eefc</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[protocol]]></category>
            <dc:creator><![CDATA[Kiarash Vosough]]></dc:creator>
            <pubDate>Tue, 06 Dec 2022 22:06:04 GMT</pubDate>
            <atom:updated>2023-01-25T21:25:32.537Z</atom:updated>
            <content:encoded><![CDATA[<h4>This article demonstrates how to have separate implementations of a method defined by two protocols with identical signatures.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*KpAPOZ-dj0mLX7snfxFkHg.jpeg" /></figure><h3><strong>Problem</strong></h3><p>The problem is that when conforming to multiple protocols, there may be a method with the same signature defined in two or more protocols.</p><pre>protocol TypeNamePrinter {<br>    func print()<br>}<br><br>protocol DetailPrinter {<br>    func print()<br>}</pre><p>For example, when a type conforms to two protocols, only one <strong><em>print()</em></strong> method must be implemented.</p><pre>struct Printer: TypeNamePrinter, DetailPrinter {<br>    func print() {<br>        print(&quot;hello there&quot;)<br>    }<br>}</pre><p>But what if it is not desired to have the same implementation for each of the protocols’ methods? When using one of the protocols as the type to store an instance of Printer, whether it is TypeNamePrinter or DetailPrinter, the same method with the same implementation will be executed.</p><pre>let printer1: TypeNamePrinter = Printer()<br>printer1.print() // will print &quot;hello there&quot;<br><br>let printer2: DetailPrinter = Printer()<br>printer2.print() // will print &quot;hello there&quot;</pre><p>However, if separate implementations are desired for each of these methods, Swift’s underscore attributes can be used to rescue.</p><h3>Here It Comes The Swift’s Underscore Attributes To Rescue</h3><p>The @_implements(ProtocolName, Requirement) attribute indicates that a function with one name satisfies a protocol requirement with a different name. This is particularly useful when two protocols declare a requirement with the same name, but the conforming type wishes to offer separate implementations.</p><pre>struct Printer: TypeNamePrinter, DetailPrinter {<br>    <br>    @_implements(TypeNamePrinter, print())<br>    func typeNameprint() {<br>        Swift.print(&quot;type&quot;)<br>    }<br>    <br>    @_implements(DetailPrinter, print())<br>    func detailprint() {<br>        Swift.print(&quot;detail&quot;)<br>    }<br>}<br><br>let printer1: TypeNamePrinter = Printer()<br>printer1.print() // will print &quot;type&quot;<br><br>let printer2: DetailPrinter = Printer()<br>printer2.print() // will print &quot;detail&quot;</pre><h3>Final Word</h3><p>In conclusion, while the underscore attribute can be useful in these situations, it is best to stick to the language’s fundamental rules and only use it when there are no other choices.</p><h3>Reference</h3><p><a href="https://github.com/apple/swift/blob/main/docs/ReferenceGuides/UnderscoredAttributes.md">swift/UnderscoredAttributes.md at main · apple/swift</a></p><p>I hope it was helpful for you. Give it a like to keep me motivated for the next awesome Swifty article. 😇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=570ecbb1eefc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Disaster Named NSHashTable]]></title>
            <link>https://medium.com/divar-mobile-engineering/a-disaster-named-nshashtable-d56b3d5c446f?source=rss-90202252b256------2</link>
            <guid isPermaLink="false">https://medium.com/p/d56b3d5c446f</guid>
            <category><![CDATA[foundation]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[objective-c]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Kiarash Vosough]]></dc:creator>
            <pubDate>Sat, 10 Sep 2022 15:46:51 GMT</pubDate>
            <atom:updated>2022-09-24T19:28:29.687Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s see how to store objects in an array with many options And Many Pitfalls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*1Nzadgg6CZzT9-uO12FHvw.jpeg" /></figure><h3><strong>Foundation And CoreFoundation Framework</strong></h3><p>As you may have noticed, there are two frameworks introduced by apple:</p><ol><li>CoreFoundation</li><li>Foundation</li></ol><p><a href="https://opensource.apple.com/source/"><strong>CoreFoundation</strong></a> is a low-level <strong><em>C</em></strong> API, but <strong>Foundation</strong> is a high-level <strong><em>Objective-C</em></strong> API. I just wanted to give you a hint to follow and learn more. For further reading, follow this <a href="https://ridiculousfish.com/blog/posts/bridge.html">link</a>.</p><p><strong>Foundation</strong> comes with a lot of handy tools. of them, which I intend to talk about, is a class named <strong>NSHashTable</strong>.</p><h3><strong>NSHashTable</strong></h3><p><strong>NSHashTable</strong> is modeled after <strong>NSSet </strong>on <strong>Foundation</strong> Framework,<strong> </strong>but it is much more flexible regarding object/memory handling.</p><p>Some features of <strong>NSHashTable</strong> are:</p><ol><li>Mutable, without an immutable counterpart.</li><li>It can hold <strong><em>weak</em></strong> references to its members.</li><li>Can <strong><em>copy</em></strong> members on input.</li><li>It can contain arbitrary pointers and use pointer identity for equality and hashing checks.</li></ol><p>It also accepts an <strong>OptionSet</strong> to configure the behavior we desire. Let’s see how it works.</p><p><strong>NSPointerFunctions.Options</strong> consist of two groups of options:</p><ol><li>Memory</li><li>Personality</li><li>Copy</li></ol><h4><strong>Memory Options</strong></h4><p>These options are related to the strategy which NSHashTable uses to hold an object.</p><ol><li>strongMemory</li><li>opaqueMemory</li><li>mallocMemory(<a href="https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/">read this</a>)</li><li>machVirtualMemory(<a href="https://developer.apple.com/library/archive/documentation/Darwin/Conceptual/KernelProgramming/Mach/Mach.html">read this</a>)</li><li>weakMemory</li></ol><p>The most useful which we use are <strong>strongMemory</strong> and <strong>weakMemory.</strong> It can aim to store elements’ references as weak or strong.</p><p>We skip <strong>strongMemory</strong> because it is similar to <strong>NSSet</strong> or <strong>NSArray</strong>.</p><blockquote>Notice that you are obligated to pick only one of the options above.</blockquote><h4>Personality Options</h4><p>These Options determine the strategy to be used by NSHashTable to distinguish or identify objects. This could be addressed by using hashValues, exactly mentioned in <strong>NSHashTable</strong>’s name.</p><ol><li>objectPersonality</li><li>opaquePersonality</li><li>objectPointerPersonality</li><li>cStringPersonality</li><li>structPersonality</li><li>integerPersonality</li></ol><blockquote>Notice that you are obligated to pick only one of the options above.</blockquote><h4><strong>Copy Option</strong></h4><p>Last but not least, this standalone option creates a copy from an object that can be stored inside an <strong>NSHashTable</strong>.</p><h3>Examples</h3><p>There are some pitfalls in using <strong>NSHashTable</strong>, so I will go through some examples and explain where and how they should be used.</p><p>Here is an example of creating an <strong>NSHashTable</strong>, which can hold a weak reference to its elements.</p><blockquote>Notice that this class already owns a static method to compose <strong>NSHashTable</strong> with the <strong>weakMemory</strong> and <strong>objectPersonality</strong> options.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9f09e4e934739653c658392cef07774/href">https://medium.com/media/e9f09e4e934739653c658392cef07774/href</a></iframe><p>You can observe the result of the code above; when we assign nil to <strong>optionalInstance</strong> and wait for 0.3 seconds, the number of items inside the <strong>NSHashTable</strong> becomes zero.</p><h3>Pitfalls</h3><p>Not everything in this world is perfect, NSHashTable is not an exception, but it has some wired pitfalls, which are listed below.</p><h4>Pitfall Number 1</h4><p>You might notice why the last print was executed with delay. The reason can be found on Apple’s docs which said</p><blockquote>Entries are not necessarily purged right away when the weak object is reclaimed.</blockquote><p>That is an inconvenient behavior by <strong>NSHashTable</strong>, which can be solved using <strong>allObjects</strong>’s array count, which always returns valid data.</p><h4>Pitfall Number 2</h4><p>The count property on the object won’t reflect the changes correctly even if you wait a considerable amount of time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36573870ced554cfa515e7f9d3395304/href">https://medium.com/media/36573870ced554cfa515e7f9d3395304/href</a></iframe><blockquote><strong>count</strong> returns the number of references currently in the hash table, some of which may be null. That is the reason why the count reports the wrong number.</blockquote><h4>Pitfall Number 3</h4><p>The most wired thing happens when you try to store Foundation types like NSString, NSIndexPath, etc. Even if you make the instance optional and nil, they will exist inside <strong>NSHashTable</strong> objects.</p><h4>wired right?🫤</h4><p>I searched a lot across the internet but did not find anything documented. My theory is that the reference of Immutable classes in <strong>Foundation</strong> is kept somewhere and prevents the object from being released.</p><p>An interesting part is using the mutable classes on <strong>Foundation</strong> like <strong>NSMutableString</strong>, <strong>NSMutableData</strong>, etc.</p><p>They work exactly as expected😵‍💫😵‍💫😵‍💫😵‍💫😵‍💫😵‍💫😵‍💫😵‍💫😵‍💫😵‍💫😵‍💫😵‍💫😵‍💫😵‍💫😵‍💫😵‍💫😵‍💫😵‍💫!!</p><p>Try the codes below, and you will see that <strong>NSHashTable</strong> will be empty after we remove the reference to <strong><em>str</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27865c00cb520445cf9b48a669fb4269/href">https://medium.com/media/27865c00cb520445cf9b48a669fb4269/href</a></iframe><h4>Pitfall Number 4</h4><p>Again there is some issue with Foundation classes under the following conditions:</p><ol><li>Using Swift</li><li>Using Mutable Classes Of Foundation(<strong>NSMutableString</strong> ….)</li><li>Set The NSHashTable’s option to <strong>copy</strong>.</li></ol><blockquote>Notice, This issue will not raise if you use Objective-C language while the classes are available on objc.</blockquote><p>The reason is that when you are using copy option, NSHashTable somehow creates a copy with different types which were not ported into swift.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e808fd02ada9a244a16c40058f86163/href">https://medium.com/media/6e808fd02ada9a244a16c40058f86163/href</a></iframe><p>The code above will result in a crash, and the error will be:</p><pre><strong>Fatal error: NSArray element failed to match the Swift Array Element type, Expected NSMutableData but found _NSZeroData</strong></pre><p>It seems that the <strong>_NSZeroData </strong>and several more classes are some interfaces that are internal classes of <strong>Foundation</strong> and can not be used on swift. But if you try it with Objective-C, it won’t raise any issue.</p><p>I hope Apple will fix these issues or clarify why this is happening. Until then, the more swift way can be found on this link thanks to ihor😎:</p><p><a href="https://ihor.pro/making-an-implicit-array-of-weak-references-using-weak-container-and-property-wrapper-ba07e9295c8">Making an implicit array of weak references using Weak Container and Property Wrapper</a></p><p>I hope you find this helpful article, Have a lovely weekend🥳</p><h3>References</h3><ul><li><a href="https://stackoverflow.com/questions/16323908/why-variable-with-weak-qualifier-retains-an-object">https://stackoverflow.com/questions/16323908/why-variable-with-weak-qualifier-retains-an-object</a></li><li><a href="https://stackoverflow.com/questions/16323908/why-variable-with-weak-qualifier-retains-an-object">https://stackoverflow.com/questions/16323908/why-variable-with-weak-qualifier-retains-an-object</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d56b3d5c446f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/divar-mobile-engineering/a-disaster-named-nshashtable-d56b3d5c446f">A Disaster Named NSHashTable🤯</a> was originally published in <a href="https://medium.com/divar-mobile-engineering">Divar Mobile Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structural Mocking In Swift]]></title>
            <link>https://medium.com/divar-mobile-engineering/structural-mocking-in-swift-a623b41487e0?source=rss-90202252b256------2</link>
            <guid isPermaLink="false">https://medium.com/p/a623b41487e0</guid>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Kiarash Vosough]]></dc:creator>
            <pubDate>Sat, 06 Aug 2022 11:39:28 GMT</pubDate>
            <atom:updated>2022-08-06T11:39:28.384Z</atom:updated>
            <content:encoded><![CDATA[<p>I will demonstrate how to mock with a simple structure in this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*2TmtzNgQiVOrrHIkP4Zy8w.jpeg" /></figure><h3><strong>Introduction To Mocking</strong></h3><p>As you may be familiar with other Mocking Framework, they are built on top of a Reflection feature, Allowing the framework to manipulate and modify classes in runtime and replace some implementation with their mocks, stubs, or spies.</p><p>But reflection is a threat for two reasons:</p><ol><li>Defeats Static typing</li><li>Security</li></ol><p><strong>Reflection defeats notably static typing</strong> and can lead to run-time errors. This is what Swift was designed to be safe from the beginning. Swift is a compile-time or static typing language, meaning that all the safety checks should be performed on compilation so that the errors won’t arise on runtime and causes a crash. Reflection violates the safety of Swift.</p><blockquote>Note that swift has reflection, but it is readOnly, which means there is no way to modify classes.</blockquote><blockquote>Except for those classes that inherit NSObject. That wouldn’t be swift, though:)))</blockquote><p><strong>Reflection</strong> is a security threat for apps that demand maximum data quarantine. A reverse engineer can easily decompile the code and add an extension that modifies the source code.</p><p>Does the question arise of how to mock objects in Swift?</p><h3>How To Address Mocking In Swift</h3><p>A bunch of libraries can be used to generate mocks or streamline the mocking procedure. For instance, the one I am obsessed with is <a href="https://github.com/krzysztofzablocki/Sourcery">Sourcery</a>.</p><p>But why should we use a complex library to mock the objects?</p><p>Are they reliable and can test anything?</p><p>What if some changes occurred and failed all written tests so far?</p><p>Does it provide a significant advantage?</p><p>Many advocates of unit testing, including <a href="https://twitter.com/unclebobmartin">Uncle Bob</a>, often say that <a href="https://sites.google.com/site/unclebobconsultingllc/blogs-by-robert-martin/mocking-mocking-and-testing-outcomes">mocking frameworks are overused</a>.</p><p>So what advice does Uncle Bob give <a href="https://blog.8thlight.com/uncle-bob/2014/05/10/WhenToMock.html">about not using mocking frameworks</a> — something Swift developers will need to get used to:</p><blockquote><em>I don’t often use mocking tools. I find that if I restrict my mocking to architectural boundaries, I rarely need them.</em></blockquote><blockquote><em>Mocking tools are potent, and there are times when they can be pretty helpful. For example, they can override sealed or final interfaces. However, that power is seldom necessary; and comes at a high cost.</em></blockquote><blockquote><em>Mocking across architectural boundaries is </em>easy<em>. Writing those mocks is </em>trivial<em>.</em></blockquote><blockquote><em>Writing your mocks forces you to give those mocks </em>names<em> and put them in particular directories. You’ll find this helpful because you will likely reuse them from test to test.</em></blockquote><blockquote><em>Writing your mocks means you have to </em>design<em> your mocking structure. And that’s never a bad idea.</em></blockquote><p>In Swift, there is no other choice than to follow the advice from Uncle Bob: <strong>write your mocks</strong>. It’s a proven and sustainable approach — still, <strong>it would have been nice to have a choice</strong>.</p><h3>Composing A Structure For Mocking</h3><p>The mock testing process has four main steps:</p><ol><li>Given</li><li>Expect</li><li>When</li><li>Then</li></ol><p>The structure is going to handle steps 2 and 4. Here is what should be created:</p><ol><li>A protocol that mock objects can conform to(<strong>Mock</strong>).</li><li>A class that manages the expectations and factual results(<strong>MockActions</strong>).</li></ol><p>Starting by <strong>Mock</strong>:</p><p>There should be an Action type for setting expectations that can be inside the mocks. We can put as many actions as for the mock object. It is best practice to use Enum for action, which will be covered shortly on examples.</p><p>The two methods register and verify take the responsibility of registering action inside mocks and verify it from outside.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vSk2h-Rmql3Ht28MRiMG_w.png" /></figure><p>Let’s see what <strong>MockAction</strong> does:</p><p><strong>MockAction</strong> is responsible for holding expectations and factual and also verifying whether the expectations are fulfilled or not.</p><p>Before comparing expectations and factual, we also check if any factual are ignored or not by filtering them with the help of <strong>shouldIgnoreAction.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ERwq37jGQWPelj9QzYkpaQ.png" /></figure><h3><strong>Example</strong></h3><p>Consider the service below that converts any number of different bases to Decimal.</p><p>First, the mock conforms to Mock protocol and defines its Action.</p><p>Then the method which should be tested can register some actions that can be verified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6FIGg3UY8DpUBwGyp1vslg.png" /></figure><h4>Time For Testing</h4><p>As mentioned before, the four steps for a unit test are Compliance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZsMf_mcLPN-Uibh28yhshg.png" /></figure><p>Congrats, you have learned to use such a simple structure for mocking and release yourself from using a framework or library. Uncle bob appreciates that:)))</p><p><a href="https://github.com/kiarashvosough1999/Mockia">Link to the Codes</a></p><p>The project <strong>Mockia</strong> is in its first steps 🥹 and I will try to develop it continuously. Also, your ideas and pull request are welcomed.</p><p>Have a lovely Weekend, fellas.😎😎😎</p><h3>References</h3><ol><li><a href="https://blog.pragmaticengineer.com/swift-the-only-modern-language-with-no-mocking-framework/">https://blog.pragmaticengineer.com/swift-the-only-modern-language-with-no-mocking-framework/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a623b41487e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/divar-mobile-engineering/structural-mocking-in-swift-a623b41487e0">Structural Mocking In Swift</a> was originally published in <a href="https://medium.com/divar-mobile-engineering">Divar Mobile Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sort Collections Even Easier In Swift]]></title>
            <link>https://medium.com/divar-mobile-engineering/sort-collections-even-easier-in-swift-f22502ef5bec?source=rss-90202252b256------2</link>
            <guid isPermaLink="false">https://medium.com/p/f22502ef5bec</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Kiarash Vosough]]></dc:creator>
            <pubDate>Sat, 30 Jul 2022 16:06:18 GMT</pubDate>
            <atom:updated>2022-07-30T16:06:18.406Z</atom:updated>
            <content:encoded><![CDATA[<p>Are you tired of using closure to define comparison strategy or the sort method multiple times for sorting collections? Here is the <strong>Solution</strong>😎</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*USYsBxsL8n3OwXlUYuAQZg.png" /></figure><h3>Introduction</h3><p>There are many ways to sort an array in swift; one way is to use the <strong>sort</strong> method on the <strong>MutableCollection </strong>protocol.</p><p>Since now the method which we used was this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*agKlxdYRPqd2bpyJLxGsFw.png" /></figure><p>Or this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oY91WDnqhA1K9q7WzeIgLw.png" /></figure><p>Or even the harder way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Umxq2YegJaEjucZ2pLuP1w.png" /></figure><p>So this pure function takes a closure to handle its task, but what if there was another way except using closures.</p><p>And Here it comes, The <strong>SortComparator.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*mk5C48KHxeULhmFnHs9X5w.jpeg" /></figure><h3>What is <strong>SortComparator</strong>?</h3><p><strong>SortCamparator</strong> is a protocol in which every object that conforms to it provides a comparison algorithm and storage for the sort order to use when comparing.</p><p>There are two prepared types(thanks to apple) to use:</p><p>1 . KeyPathComparator</p><p>2. SortDescriptor</p><p>Yeah, you heard me <strong>SortDescriptor</strong> is now a part of the Swift standard library and can be used instead of old-school <strong>NSSortDescriptor</strong>. But it requires that the <strong>Comparable Type</strong> inherits <strong>NSObject </strong>and that the properties should be visible to the <strong>Objective-C</strong> runtime.</p><p>Yeah, Old-School Apple!!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*sfJ8ioofmP63_3v7evMpwg.jpeg" /></figure><p>I am going to skip SortDescriptor for the sake of not exposing the variables to objc runtime and using struct. So Let’s see the example of how to use KeyPathComparator:</p><p>Suppose we have this data source and we want to sort it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ucGgYhvlQIOgrS1bldLgUA.png" /></figure><p>Here is the way to use <strong>KeyPathComparator</strong>, easy peasy. Specify the keyPath of the property on which the sort should be based. The order is also set to <strong>reverse</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jC-f6OFws8X0OEb808huJA.png" /></figure><h4>How about several KeyPath to be used in sort?</h4><p>No problem!!🥳</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Orxvu9AIo8BpUXYCDgs1bQ.png" /></figure><h4>Bonus Part</h4><p>The exciting part is that <strong>KeyPathComparator</strong> also accepts another <strong>SortCamparator</strong> to compare the specified property if it is not comparable. It could be helpful when one or many custom types (maybe of kind collection) are composited inside each other.</p><p>Let’s see an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*65njVCOMz3t9jEU6z-fnaw.png" /></figure><p>Here we aim to sort players by their scores, but score property is a collection, so we should clarify how to compare it. So another KeyPathComparator is used and sorted by the array&#39;s first value. It can be seen in the result that our players are sorted based on the first score they had.</p><p>I hope you enjoyed it, and it was helpful🫠</p><p>Until the Next article. Byeee😁👋🏻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f22502ef5bec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/divar-mobile-engineering/sort-collections-even-easier-in-swift-f22502ef5bec">Sort Collections Even Easier In Swift</a> was originally published in <a href="https://medium.com/divar-mobile-engineering">Divar Mobile Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create Publisher For UIControl]]></title>
            <link>https://medium.com/divar-mobile-engineering/create-publisher-for-uicontrol-b74ff5871787?source=rss-90202252b256------2</link>
            <guid isPermaLink="false">https://medium.com/p/b74ff5871787</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[uikit]]></category>
            <dc:creator><![CDATA[Kiarash Vosough]]></dc:creator>
            <pubDate>Fri, 22 Jul 2022 19:36:22 GMT</pubDate>
            <atom:updated>2022-07-30T16:03:54.709Z</atom:updated>
            <content:encoded><![CDATA[<p>This article will teach you how to listen to UIControl’s events with combine’s publisher.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pS-99Go_6l55MvuyBxcT0w.png" /></figure><h3><strong>Introduction</strong></h3><p>Combine is a reactive framework developed by Apple, and it was released in IOS 13.</p><p>Unlike RxSwift, which has a separate library named RxCocoa to Provide Cocoa-specific capabilities for general iOS/macOS/watchOS &amp; tvOS app development, Combine did not have such an extension. So it became a nightmare for developers to implement an interface to adopt a Combine’s stream for UIElement’s events.</p><p>This article will demonstrate that this nightmare was a misunderstanding and clarify that creating a custom publisher was never so easy.</p><blockquote>I will not go through the details of Combine Elements, so the reader is assumed to have enough knowledge about reactive programming, specifically Combine Framework.</blockquote><h3><strong>Publisher</strong></h3><p>So what are publishers? as apple said:</p><blockquote>Declares that a type can transmit a sequence of values over time.</blockquote><p>To start the process, we first need a publisher whose subscribers can send their requests and receive a subscription if possible.</p><ol><li>Create a struct (with a generic type C) that conforms to <strong>Publisher</strong> protocol.</li></ol><p>The <strong>C</strong> will be used as the publisher&#39;s output, and for now, the Failure is set to Never. To reference the C and the event, they shall be received in the initializer and stored inside the struct. They are necessary to create a Subscription.</p><blockquote>For the sake of not creating leaks, we can store the Control as a weak reference.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AGuJJLjfajF_ZNs63TMcOg.png" /></figure><h4>What does the <strong>receive</strong> do?</h4><p>The <strong>received</strong> method acknowledges the subscribe request and returns a <strong>Subscription</strong> instance. The subscriber uses the subscription to demand elements from the publisher and can use it to cancel publishing.</p><p>So let us create a custom <strong>Subscription</strong> and then go back and complete the Publisher implementation.</p><h3><strong>Subscription</strong></h3><p>As Apple said:</p><blockquote>A protocol representing the connection of a subscriber to a publisher.</blockquote><p>The next step would be:</p><p>2. Create a class (with S and C generic type) that conforms to <strong>Subscription</strong> and implement the methods.</p><p>This stage depends on the <strong>control</strong> because the <strong>addTarget</strong> method should be used to register a selector and receive the events; also, the subscribers should be notified about the event, so storing a reference to <strong>Subscriber</strong> is mandatory<strong> </strong>too.</p><blockquote>You can forget about storing control and its generic type,<strong> </strong>but you will be able to just send UIControl as an output(which is a parent class) and not the specific type of the control you are using.</blockquote><p>On the <strong>handleEvent</strong> method, the subscribers should be notified about the event; it is done by calling <strong>receive</strong> method and passing it control as an argument.</p><p>As you may know, when a subscription is about to be disposed of DisposeBag, the cancel method is called, so it is obligatory to discard everything which was retained. Here the target is removed from the control(The safety actions were done before by declaring control as a weak reference).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5hB9GPrVYxVuFh65o_ynGw.png" /></figure><p>Let us get back to the <strong>Publisher.</strong></p><p><strong>3.</strong> First, check whether the control still has value; if not, send completion to the subscriber, meaning that the stream is finished.</p><p>Then create an instance of <strong>InteractionSubscription</strong> and provide the subscriber with it. When the <strong>publisher</strong> receives a <strong>Subscriber</strong>, it will make a <strong>subscription</strong> and respond to the request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bqOXVb9UvdvoO9uS0NhYqQ.png" /></figure><p><strong>4. </strong>Create a protocol that inherits from UIControl, and add this method:</p><p>A different protocol is used because the covariant Self can only appear at the top level of the method result type. So a protocol is used to address this limitation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V5jdqAgBzcepv23C6L0Gcw.png" /></figure><p>And All done, Was it tough to implement nearly 60 lines of code to adopt Combine Streams in UIKit?🧐</p><h4>Certainly Not.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*8Vnkcjh643NYRb0DqzeTNw.jpeg" /></figure><h3>Usage</h3><p>here is how to use the publisher. Easy peasy!😁</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*02ZZ9mB5YH_A-MFyX02H0A.png" /></figure><p>I hope you enjoyed it, and it comes in handy for those who argue about reinventing the wheel or such stuff:)))) sometimes reinventing stops us from adding a massive dependency to our project.</p><p>The complete implementation is available on my <a href="https://gist.github.com/kiarashvosough1999/2c5936350743b7d097bea00bc4028414">gist</a>.</p><p>Have a lovely weekend😎😎.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b74ff5871787" width="1" height="1" alt=""><hr><p><a href="https://medium.com/divar-mobile-engineering/create-publisher-for-uicontrol-b74ff5871787">Create Publisher For UIControl</a> was originally published in <a href="https://medium.com/divar-mobile-engineering">Divar Mobile Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Singleton Pattern Or Not?]]></title>
            <link>https://medium.com/divar-mobile-engineering/use-singleton-pattern-or-not-282b197a2e9f?source=rss-90202252b256------2</link>
            <guid isPermaLink="false">https://medium.com/p/282b197a2e9f</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Kiarash Vosough]]></dc:creator>
            <pubDate>Tue, 19 Jul 2022 14:26:29 GMT</pubDate>
            <atom:updated>2022-07-30T16:07:34.624Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will go through the cons and pros of the singleton pattern, and in much more detail, I will answer the question above.</p><h3>Where are Singletons Supposed To Be Used?</h3><p>Let’s start with a definition of this pattern by referring to <a href="https://refactoring.guru/design-patterns/singleton">refactoring.Guru</a>.</p><blockquote><strong>Singleton</strong> is a creational design pattern that lets you ensure that a class has only one instance while providing a global access point to this instance.</blockquote><p>It is also mentioned that this pattern addresses two problems:</p><ol><li><strong>Ensure that a class has just a single instance.</strong></li><li><strong>Provide a global access point to that instance.</strong></li></ol><h3><strong>Issue With Global Instances</strong></h3><p>Wait, what, global access? So everyone can access it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*2hYtUjaAjiV4GPQNnvPGIA.png" /></figure><blockquote>By using singletons, you almost always sacrifice transparency for convenience.</blockquote><p>The question arises: Do you sacrifice for a bit of convenience, Not to pass around instances to avoid some boilerplate code!?</p><p>By using global instances, you hide your application&#39;s dependencies in your code instead of exposing them through the interfaces and injecting them wherever is needed. Besides this is a <a href="https://en.wikipedia.org/wiki/Code_smell">CodeSmell</a>, considered a bad design practice that causes trouble in the future and increases the risk of bugs.</p><blockquote>Even when I started computer science in university, our mentor told us to avoid global variables or instances; maybe he knew I would reach this stage someday :)))</blockquote><h3>Violation Of Solid Principles</h3><p>The nature of singleton violates three principles, and I am going to talk in much more detail about these horrible violations.</p><h4>Singletons vs. Single Responsibility Principle</h4><p>Singleton generally comes from the fact that it breaks the SRP. A singleton has two responsibilities:</p><ol><li>Manage the creation of the instance of the class</li><li>Do something that is the original responsibility of the class</li></ol><p>Singleton should also manage the access to the instance, more precisely when several threads request access to one instance; singleton should take responsibility for dispatching data to each request in threads by using locks to prevent <strong>Race-Condition</strong> or handling read and write to deliver valid data instead of an invalidated data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*1rbPeV4YLRwCpDZ-EZ5ElQ.jpeg" /></figure><p>This is just the beginning. As time goes by, new responsibilities will be added to the singleton. You end up with a class that nearly does anything. This will cause other problems which are going to be covered.</p><h4>Singletons vs. Open/Close</h4><p>Singletons break the Open/Closed Principle because the singleton class is in control over the creation of its instance, while consumers will typically have a hard dependency on its concrete instance. This disallows the implementation to be changed without having to make sweeping changes throughout the application.</p><p>For a class to be “open” it must be possible to inherit from it. Inheritance is an “is-a” relationship. If you inherit from a singleton-class then instances of the child-class are also instances of the parent class due to the “is-a” relationship, meaning you can suddenly have multiple instances of the singleton class.</p><p>If the singleton class inhibits inheritance, it’s no longer “open” on the other hand, If a singleton class allows inheritance then it is “open” for extension, then it can no longer enforce the singleton pattern.</p><p>This also led us to a new issue, which makes refactoring harder. It is also known as a brittle assumption. The assumption that there will ever be only one instance or some method inside it is often broken during a project’s lifetime, and this pattern structures the code in a way that requires a very significant effort to refactor when this assumption is inevitably wrong.</p><blockquote>For those who are IOS developers. Just imagine that apple removed the <strong>NotificationCenter</strong> or <strong>UserDefault</strong> or even deprecated their methods. If you’ve used the Singleton of these classes all over your project, <strong>who</strong> will take the responsibility of removing deprecated API all over an app at scale?</blockquote><p>Answer to a question: Couldn’t a singleton implement an interface to solve this problem?</p><p>Answer: If it had the interface, the instance would be replaceable; this wouldn&#39;t follow the Singleton pattern, while there should be only one instance of a singleton class.</p><h4>Singletons vs. Dependency Inversion Principles</h4><p>The biggest problem is here, violating DIP. Because consumers will always depend directly on the concrete class to get the instance, while the DIP prescribes the use of abstractions, this causes the Singleton implementation to be dragged along and disallows adding cross-cutting concerns by wrapping the implementation in a decorator or distributing the client without that singleton implementation.</p><p><strong>Again, answer the last question</strong>: Couldn’t a singleton implement an interface to solve this problem?</p><p>No, instance property would still be defined on the static class, which causes the DIP to be violated again.</p><h3>How does Singleton Affect Testing?</h3><p>This increased coupling due to the Singleton design pattern makes creating <strong>Mocks</strong> and <strong>Stubs </strong>during unit tests tricky. In other words, using the Singleton design pattern makes your life painful when writing unit tests since it becomes tough to identify the dependency chains so that the components in your application can be unit tested adequately. Most importantly, you must use static methods when implementing the Singleton design pattern. Static methods make unit testing difficult since you cannot <strong>mock</strong> or <strong>stub</strong>. In essence, the types in your application that have a dependency on a singleton class are relatively difficult to unit test. In unit testing, each unit test should be independent of one another. Another reason the Singleton design pattern makes your life difficult in unit testing is that they remain alive in the application. Hence they persist in the state as long as the application remains in the memory.</p><p>Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no for unit tests. Because each unit test should be independent of the other. So how will you solve the dependency between these states in each unit?</p><h3>Conclusion</h3><p>Care about programming principles since they help you write good code and avoid using patterns that violate these principles. On the other hand, if you feel that some of the principles restrict you and your code would be better without it, do not hesitate to consider writing a code that breaks the principles. Discuss it with your peers and conclude. The conclusion will be that you were wrong, considering breaking Solid Principles in 90% of the cases. In 10%, however, you may come up with brilliant ideas😁. But always keep thinking of the future of the software you are developing, do not tie up everything for the next developers, and do not increase the maintenance cost.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=282b197a2e9f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/divar-mobile-engineering/use-singleton-pattern-or-not-282b197a2e9f">Use Singleton Pattern Or Not?</a> was originally published in <a href="https://medium.com/divar-mobile-engineering">Divar Mobile Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Labeling For Loop In Swift]]></title>
            <link>https://medium.com/@vosough.k/labeling-for-loop-in-swift-2afac8882cc7?source=rss-90202252b256------2</link>
            <guid isPermaLink="false">https://medium.com/p/2afac8882cc7</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[tricks]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Kiarash Vosough]]></dc:creator>
            <pubDate>Sun, 01 May 2022 17:31:24 GMT</pubDate>
            <atom:updated>2022-05-01T17:34:50.963Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever think of breaking from inner nested loops to the outer ones? Follow up for the trick!</p><h3>Introduction</h3><p>Swift has a built-in <strong>break</strong> keyword. <strong>break </strong>allows us to exit the loop it was written inside, but what if you wanna break the whole loop from the inner one?</p><h3><strong>Swift Labeling Statement</strong></h3><p>Label statement allows us to mark each for-loops, and with the help of the <strong>break</strong> keyword, we can break any number of loops.<br>Let us see an example to clear this up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5lM3rt6lesaYywRajGeXnw.png" /></figure><p>This code aims to find the first even number and exit quickly, but if you execute this code, you notice that the first loop will continue to iterate. So what we should do is use a <strong>label</strong> statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vf94mGIsmNyEIEQbtjk7Lg.png" /></figure><p>So the first loop is labeled. Inside the inner loop, we break to this label. So the break statement will break the outer loop whenever an even number is found. If you run this code on the playground, you notice that the “<strong>Loop Still going on</strong>” will not be printed anymore.</p><h3><strong>Last Word</strong></h3><p>This feature might seem not so helpful, but it is still a feature and can be used in some situations to untie our knots. Plus, It was one of my interview questions 😬.</p><p>Do not forget to it a like if you like it. Goodbye until the Next Article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2afac8882cc7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Numbers (Part 2)]]></title>
            <link>https://medium.com/@vosough.k/swift-numbers-part-2-4f38f1342e21?source=rss-90202252b256------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f38f1342e21</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[numbers]]></category>
            <dc:creator><![CDATA[Kiarash Vosough]]></dc:creator>
            <pubDate>Fri, 08 Apr 2022 11:44:53 GMT</pubDate>
            <atom:updated>2022-04-08T19:12:15.166Z</atom:updated>
            <content:encoded><![CDATA[<p>Move Your Knowledge About Numbers To Next Step</p><h3>Introduction</h3><p>So far we have covered three protocols: <strong>Equatable</strong>, <strong>Comparable</strong>, and <strong>Strideable</strong> in the last <a href="https://medium.com/@vosough.k/swift-numbers-7d99d0feccb">article</a>. Little by little, we are expanding our knowledge about numbers in Swift and this is the second step, so let’s dive into it.</p><h3>What is going to be covered?</h3><p>Let’s begin by covering 2 more protocols: <a href="https://developer.apple.com/documentation/swift/additivearithmetic"><strong>AdditiveArithmetic</strong></a> and <a href="https://developer.apple.com/documentation/swift/numeric"><strong>Numeric</strong></a>.</p><p>As we go forward and explain these two protocols, you will observe that the basis of numbers is forming from these two important protocols, So it is a big step for us in this series.</p><p>One Great news🔥: I’m going to demonstrate a real example using <a href="https://docs.swift.org/swift-book/LanguageGuide/Properties.html"><strong>PropertyWrapper</strong></a> that can be used in products and actually it was somehow one of my interviews questions Just to encourage you to learn different <strong>Swift</strong> <strong>Protocols</strong> including these ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*tsd_7krvv7Ty1lCjFmfEWQ.jpeg" /></figure><h3>AdditiveArithmetic</h3><p>So what is the <strong>AdditiveArithmetic</strong>? what is its purpose and what is it going to add to our types?</p><p>Let’s see the apple description which always becomes a great document for any Swift developers.</p><blockquote>A type with values that support addition and subtraction.</blockquote><p>Wait, that’s it…??🤯</p><p>The answer is yes, as easy as possible. This protocol adds addition and subtraction to whatever type conforms to it. But wait, it also has a variable that returns the identity element of that type. How awesome, we have the behavior of basis of mathematics!!</p><p><strong>AdditiveArithmetic</strong> is awesome but it is not doing any magic, So It is necessary and mandatory to implement 2 methods and one variable.</p><ol><li>Subtraction Operator Overloading (-)</li><li>Addition Operator Overloading (+)</li><li>The Static Identity Variable</li></ol><p>The rest of the methods you might see on Xcode has default implementation based on these methods, so no need to implement them all except if you wanna change their behaviors.</p><blockquote>Notice that it conforms to <strong>Equatable.</strong>️️</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FWcA0baMv4wq42-w9bz2Ow.png" /></figure><p>Let’s explain it deeply by an example.</p><p>Assume that we wanna hold a <strong>PayCheck</strong> and we want two PayCheck to be subtracted and realized the difference between two months&#39; income or to sum them. This is what we can implement with <strong>AdditiveArithmetic.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g2EouHntExMTob7HxNm_BA.png" /></figure><p>Start defining our PayCheck struct and this type should conform to <strong>AdditiveArithmetic.</strong></p><p>First, the identity variable should be declared, the identity element for PayCheck is the gross income and tax equal to zero so no matter how many times we sum this element with different PayCheck we always get the same first PayCheck.</p><p>Second, the (+) operator should be defined. The compiler itself does not know how to sum two gross salaries or taxes so we should guide him/her(What is the compiler gender? IDK), we are doing so by defining this method, and of course, it returns a <strong>PayCheck</strong> because we are summing two <strong>PayChecks</strong> and we wish to see the same type as result(you can’t sum two apples and get a banana instead!!).</p><p>The (-) operator is the third to be implemented just like (+) but vice versa this time we subtract the gross salaries and taxes.</p><p>Building <strong>PayCheck</strong> is over. Let’s see the result and magics. Time to add and subtract some money.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uXPCeV57CJ2ZG_qdW7Dtog.png" /></figure><p>Here are defined two-month <strong>PayChecks</strong> of mine. I want to know how much got demoted from last month. I start to subtract the two-month PayChecks and the result is 5000$ and 0.39 tax included(don&#39;t be lazy like me or tolerate this much demotion.), when we put (-) between two variables of type <strong>PayChecks </strong>compiler automatically refers to the method we wrote and realize what he/she should do with this expression. The same goes with (+) of course.</p><blockquote>Sure, you can just write these methods in your type(Class, Enum, Struct), but the purpose is to implement the behavior and use these behaviors of additive and subtractive without bounding ourselves to specific types. As an example, you have a method that subtracts two generic parameters that conform to <strong>AdditiveArthimetics. </strong>We don’t care what two variables are, the purpose of the method is to subtract them. we satisfied these needs by using protocol-oriented programming and specifically here <strong>AdditiveArthimetics.</strong></blockquote><h3>Numeric</h3><p>So until here, we have the basis of mathematics, but we are lazy (at least I am) and we always looking for making life easier. So the next mathematics operator we wanna add to our type is multiplication in order not to sum a type different times with itself.</p><p>First, let’s see the apple description of this protocol:</p><blockquote>A type with values that support multiplication.</blockquote><p>As straight as possible. Let’s dive into code now. shall we?</p><p>First, take a look at the protocol and the things we must implement:</p><blockquote>Notice that Numeric also conforms to <strong>AdditiveArthimetics</strong>. why because every operator in mathematics are based on addition and subtraction.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P1h2i7RvMpMnS-x6pGN4Mw.png" /></figure><p>What is that failable init? well I am not going to discuss the <a href="https://developer.apple.com/documentation/swift/binaryinteger"><strong>BinaryInteger</strong></a> right now, but what this init does is to take any type that conforms to BinaryInteger and try to init self if it is possible, as an example, all the types of Int conform to <strong>BinaryInteger</strong> and <strong>Numeric</strong> but if we try to initialize Int8 with this initializer and the value 10_000 it returns nil, why? because Int8 accept range is from -128 to 127.</p><p>Next is the Magnitude type which is mandatory to be clarified, As you know there is a symmetric number for any number. What the magnitude variable does is return the absolute value of the current value stored in our type. You guessed right it works like the <strong>abs</strong> function. The good news is Magnitude can be any type that is <strong>Numeric</strong> and <strong>Comparable</strong>, It shouldn’t be the same type as Self necessarily.</p><p>The most important is the overloading (*) operator where the purpose of Numeric is satisfied completely.</p><p>I’m going to demonstrate a production example. Assume that you want to build a <strong>PropertyWrapper</strong> that takes any Mile number and multiplies it by 2 (now for the sake of not facing an error I’m not using 1.6 which is a double) to transform it into Kilometer and by any number I mean a double, float, or integer or any type that conform to Numeric.</p><p>we can achieve that by writing the <strong>PropertyWrapper</strong> like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C6dAdsTKwzu-QXudz7A8tA.png" /></figure><p>I hold the mile value in <strong>WrappedValue</strong> so we can access the initial value at any time and I used the <strong>ProjectedValue</strong> to project the kilometer value whenever needed. Here is the test class for our tiny <strong>PropertWrapper</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zb-gVZQhEBBfnAaciwFOCA.png" /></figure><p>And when we run this piece of code we observe that no matter which type are the variables, the <strong>projectedValue</strong> was able to multiply the number by 2 and return the result. That’s because all three types Int, Double, and float conform to <strong>Numeric,</strong> and multiplication is defined for them.</p><h3><strong>Conclusion</strong></h3><p>We’ve seen some protocols until now, and we observed how they can be used. I encourage you to take a look at other sources and of course <strong>AppleDocs</strong> for more information.</p><p>What we learned until now as a Diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*ZRp6Hzj0MJa3OP1JMsBkWA.jpeg" /></figure><blockquote>Numeric Protocol was the answer to one of my interview question for the company I am now working for, As it comes very handy most of the times we are writing genrics code and it becomes interesting on interviews to make questions out of it. So take the Swift protocols seriously:)</blockquote><p>I appreciate that you made it through here. I am going to write the next part as soon as possible😊.</p><p>Thank you for your time and support. Don&#39;t forget to give it a like if you enjoyed it. Have a nice weekend fellas.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f38f1342e21" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>