<?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 Shobhit Gupta on Medium]]></title>
        <description><![CDATA[Stories by Shobhit Gupta on Medium]]></description>
        <link>https://medium.com/@shobhitgupta-27686?source=rss-596dececf765------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*feYnZGPNM1mNWXds.</url>
            <title>Stories by Shobhit Gupta on Medium</title>
            <link>https://medium.com/@shobhitgupta-27686?source=rss-596dececf765------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 18:37:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shobhitgupta-27686/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[COPY-ON-WRITE-OPTIMIZATION]]></title>
            <link>https://shobhitgupta-27686.medium.com/copy-on-write-optimization-97e43eb8af01?source=rss-596dececf765------2</link>
            <guid isPermaLink="false">https://medium.com/p/97e43eb8af01</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Shobhit Gupta]]></dc:creator>
            <pubDate>Thu, 11 Mar 2021 09:59:17 GMT</pubDate>
            <atom:updated>2021-03-11T10:51:38.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i_7ee7EVYUvslCO_8UA1bw.png" /></figure><p><strong>Introduction :-</strong></p><p>The most basic distinguishing feature of a value type is that copying — the effect of assignment, initialization, and argument passing — creates an independent instance with its own unique copy of its data.</p><p>In this article, I explain an optimisation of this copying: the copy-on-write.</p><h3>What Is Copy-On-Write?</h3><p>Every time we assign a value type to another one, we have a copy of the original object:</p><pre>let myString = &quot;Hello&quot;<br>var myString2 = myString            // myString is copied to myString2<br>myString2.append(&quot; World!&quot;)<br><br>print(&quot;\(myString) - \(myString2)&quot;) // prints &quot;Hello - Hello World!&quot;</pre><p>If we copy just a plain String we may not have problems with the performance.</p><p>We may start having some troubles when we have Arrays with thousands of elements, and we copy them around our app. For this reason, the Array has a different way to copy, which is called copy-on-write.</p><p>When we assign an Array to another one, we don’t have a copy. The two Arrays share the same instance. In this way, we don’t have two different copies of a big Array and we can use the same instance, with a better performance. Then, just when one of the two Arrays change we have a copy.</p><p><strong>Let’s see an example:</strong></p><pre>var array1 = [1, 2, 3, 4]<br><br>address(of: array1)     // 0x60000006e420<br><br>var array2 = array1<br><br>address(of: array2)     // 0x60000006e420<br><br>array1.append(2)<br><br>address(of: array1)     // 0x6080000a88a0<br>address(of: array2)     // 0x60000006e420</pre><p>We can notice, in this example, that the two Arrays share the same address until one of them changes. In this way, we can assign array1 to other variables several times without copying every time the whole array, but just sharing the same instance until one of them changes. This is very useful for the performance of our App.</p><p><em>For your info, this is the function used to dump the address:</em></p><pre>func address(of object: UnsafeRawPointer) -&gt; String {<br>    let addr = Int(bitPattern: object)<br>    return String(format: &quot;%p&quot;, addr)<br>}</pre><p>Unfortunately, not all the value types have this behaviour. This means that, if we have a struct with a lot of information, we may need a copy-on-write to improve the performance of our App and to avoid useless copies. For this reason, we have to create this behaviour manually.</p><h3>Manual Copy-On-Write</h3><p>Let’s consider a struct User in which we want to use copy-on-write:</p><pre>struct User {<br>    var identifier = 1<br>}</pre><p>We must start creating a class, with a generic property T, which wraps our value type:</p><pre>final class Ref&lt;T&gt; {<br>    var value: T<br>    init(value: T) {<br>        self.value = value<br>    }<br>}</pre><p>We use class—which is a reference type—because when we assign a reference type to another one the two variables will share the same instance, instead of copying it like the value type.</p><p>Then, we can create a struct to wrap Ref:</p><pre>struct Box&lt;T&gt; {<br>    private var ref: Ref&lt;T&gt;<br>    init(value: T) {<br>        ref = Ref(value: value)<br>    }</pre><pre>    var value: T {<br>        get { return ref.value }<br>        set {<br>            guard isKnownUniquelyReferenced(&amp;ref) else {<br>                ref = Ref(value: newValue)<br>                return<br>            }<br>            ref.value = newValue<br>        }<br>    }<br>}</pre><p>Since struct is a value type, when we assign it to another variable, its value is copied, whereas the instance of the property ref remains shared by the two copies since it’s a reference type.</p><p>Then, the first time we change value of one the two Box variables, we create a new instance of ref thanks to:</p><pre>guard isKnownUniquelyReferenced(&amp;ref) else {<br>    ref = Ref(value: newValue)<br>    return<br>}</pre><p>In this way the two Box variable don’t share the same ref instance anymore.</p><p><a href="https://developer.apple.com/reference/swift/2429905-isknownuniquelyreferenced"><em>isKnownUniquelyReferenced</em></a><em> returns a boolean indicating whether the given object is known to have a single strong reference.</em></p><p>Here the whole code:</p><pre>final class Ref&lt;T&gt; {<br>    var value: T<br>    init(value: T) {<br>        self.value = value<br>    }<br>}</pre><pre>struct Box&lt;T&gt; {<br>    private var ref: Ref&lt;T&gt;<br>    init(value: T) {<br>        ref = Ref(value: value)<br>    }</pre><pre>    var value: T {<br>        get { return ref.value }<br>        set {<br>            guard isKnownUniquelyReferenced(&amp;ref) else {<br>                ref = Ref(value: newValue)<br>                return<br>            }<br>            ref.value = newValue<br>        }<br>    }<br>}</pre><p>We can use this wrapping like this:</p><pre>let user = User()</pre><pre>let box = Box(value: user)<br>var box2 = box                  // box2 shares instance of box.ref</pre><pre>box2.value.identifier = 2       // Creates new object for box2.ref</pre><h3>Conclusions</h3><p>An alternative to this approach is using an Array — instead of Box—to wrap the value type to copy on write. Unfortunately, the approach with the Array has some disadvantages. You can find more details in the Apple’s <a href="https://github.com/apple/swift/blob/master/docs/OptimizationTips.rst#advice-use-copy-on-write-semantics-for-large-values">optimisation tips</a>.</p><p><strong>NOTE:-</strong></p><p><em>Usage Case</em>: I think an example of a large value can be a struct with which contains an array with a lot of elements, could be the best case where you should consider use of Manual COW. Of course, it’s not something you use all days.</p><p>Thanks for the support ! Do clap if you liked the content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97e43eb8af01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Security in iOS Apps: Transport Layer]]></title>
            <link>https://shobhitgupta-27686.medium.com/security-in-ios-apps-transport-layer-ad1eb6ed6e36?source=rss-596dececf765------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad1eb6ed6e36</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Shobhit Gupta]]></dc:creator>
            <pubDate>Thu, 29 Oct 2020 15:56:59 GMT</pubDate>
            <atom:updated>2020-10-29T15:56:59.199Z</atom:updated>
            <content:encoded><![CDATA[<h3>SSL Pinning :-</h3><p>When a mobile app communicates with a server, it uses SSL pinning technique for protecting the transmitted data against tampering and eavesdropping. On a default mode, the SSL implementations used in the apps trust any server having certificates trusted by an operating system’s trust store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Lxes_KeDWrnDK3rCI-xndQ.png" /></figure><p>With SSL pinning, the app is devised to reject every but one or limited predefined certificates. When the app connects with a server, it compares the certificate with the pinned certificate. Only when there is a match, the server is trusted and SSL connection gets established. This is what makes SSL Pinning one of the best iOS app security tips that developers follow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*UcfXYSNwzPWqXfJP1JI1Bw.png" /></figure><h3>Why Do We Need SSL Pinning in iOS?</h3><p>The task of setting and maintaining the SSL session is given to a system library. It means that the app which tries to establish a connection doesn’t determine which certificate must be trusted and which shouldn’t be.</p><p>A hacker who is able to generate a self-signed certificate and add it in the operating system’s trust store is able to set up a MITM attack against apps that use a SSL. This allows them to do things that works opposite of the iOS application security tips:</p><ul><li>Read and modify all the SSL sessions and use the access for reverse engineering the app protocol or for extracting the API keys from request.</li><li>They can also hinder the SSL sessions through tricking users into installing trusted CA through malicious web pages. The root CAs which are trusted by the devices can also get compromised and can be used for generating certificates.</li></ul><p>By lowering the number of trusted iOS SSL certificates, the apps are protected from such remote attacks. It also helps eliminate the occurrence of reverse engineering — one of the biggest roadblocks in iOS app security testing.</p><h3>How does SSL work?</h3><p>SSL Pinning is one of the most common iOS app security tips. But in order to understand what it means, you will first have to know how SSL works.</p><ul><li>A browser attempts to connect with a website which is secured with a SSL. The browser then requests the web server to identify itself.</li><li>Web server then sends the browser its SSL certificate copy.</li><li>The browser checks if the SSL certificate must be trusted. If it can be, a message is sent to the web server.</li><li>Web server then sends back an acknowledgement to begin the SSL encrypted session.</li><li>The encrypted data is then finally shared between the browser and web server.</li></ul><h3>Types of SSL Certificates Pinning Implementation:-</h3><p>The implementation of SSL pinning gives you two options –</p><ul><li>Pin the certificate — you can download the server’s certificate and bundle them in the app. At the runtime, the app compares the server certificate to ones that you have embedded.</li><li>Pin the public key — you can retrieve the public key of certificate in the code as string. At the runtime, the application compared the certificate’s public key to one which is hard-coded in the code.</li></ul><p>Making a choice from between the two SSL pinning methods is dependent on your server configuration and individual needs. When you choose the first option, you will have to upload the app when the server changes its certificate or it would stop working. When choosing the second option, you might violate the key rotation policy for the public key won’t change.</p><p>Let’s now look into how to make these methods the iOS app security best practices.</p><h3>How to Implement SSL Pinning in your iOS App:-</h3><h4>1. NSURLSession:-</h4><p>In case of NSURLSession, the primary method for handling SSL pinning is URLSession:didReceiveChallenge:completionHandler:delegate. Developers will have to set the class to conform URLSessionDelegate and paste this function to the class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FJE7fcFdumHJoNcSZOIr3g.png" /></figure><p>The function would “<em>requests credentials from the delegate in response to an authentication request from the remote server</em>.” The developers will then compare certificates from the server with one saved in the app bundle. If the two certificates are found identical, authentication will let it pass and the client will be able to connect to the server.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad1eb6ed6e36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OSLog and Unified logging: Optimised]]></title>
            <link>https://shobhitgupta-27686.medium.com/oslog-and-unified-logging-optimised-ea5ef8cb1c24?source=rss-596dececf765------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea5ef8cb1c24</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[console]]></category>
            <category><![CDATA[logging]]></category>
            <dc:creator><![CDATA[Shobhit Gupta]]></dc:creator>
            <pubDate>Wed, 28 Oct 2020 09:30:03 GMT</pubDate>
            <atom:updated>2020-10-28T09:30:03.963Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KcnSQD0lFmYTdgdWgWQP2A.jpeg" /></figure><p>OSLog as a replacement of print and NSLog is the recommended way of logging by Apple. It’s a bit harder to write, but it comes with some nice advantages compared to it’s better-known friends.</p><p>By writing a small extension you make it fairly easy to replace your print statements. Using the Console app in combination with your logs can help you debug issues in a more efficient way. OSLog has a low-performance overhead and is archived on the device for later retrieval. These are two of the advantages of using OSLog instead of print statements.</p><h3>Setting up OSLog</h3><p>OSLog makes it possible to log per category, which can be used to filter logs using the Console app. By defining a small extension you can easily adopt multiple categories.</p><p><em>Note: if you’re using iOS 14 and up, there are new APIs available explained further down this post.</em></p><pre>import os.log<br><br>extension OSLog {<br>    private static var subsystem = Bundle.main.bundleIdentifier!<br><br>    /// Logs the view cycles like viewDidLoad.<br>    static let viewCycle = OSLog(subsystem: subsystem, category: &quot;viewcycle&quot;)<br>}</pre><p>This extension uses the bundle identifier of the app and creates a static instance for each category. In this case, we have a view cycle category, which we can use to log in our app:</p><pre>override func viewDidLoad() {<br>    super.viewDidLoad()<br>    os_log(&quot;View did load!&quot;, log: OSLog.viewCycle, type: .info)<br>}</pre><h3>Log levels</h3><p>The OSLog API requires to pass in an OSLogType which can be used to automatically send messages at the appropriate level. A log type controls the conditions under which a message should be logged and is another way of filtering in the Console app.</p><ul><li><strong>default (notice)</strong>: The default log level, which is not really telling anything about the logging. It’s better to be specific by using the other log levels.</li><li><strong>info</strong>: Call this function to capture information that may be helpful, but isn’t essential, for troubleshooting.</li><li><strong>debug</strong>: Debug-level messages are intended for use in a development environment while actively debugging.</li><li><strong>error</strong>: Error-level messages are intended for reporting critical errors and failures.</li><li><strong>fault</strong>: Fault-level messages are intended for capturing system-level or multi-process errors only.</li></ul><p>You can pass in a log level as a type parameter:</p><pre>/// We&#39;re logging an .error type here as data failed to load.<br>os_log(&quot;Failed loading the data&quot;, log: OSLog.data, type: .error)</pre><h3>Logging parameters</h3><p>Parameters can be logged in two ways depending on the privacy level of the log. Private data can be logged using %{private}@ and public data with %{public}@.</p><p>In the following example, we’re logging the username in both public and private to show the differences.</p><pre>override func viewDidLoad() {<br>    super.viewDidLoad()<br>    os_log(&quot;User %{public}@ logged in&quot;, log: OSLog.userFlow, type: .info, username)<br>    os_log(&quot;User %{private}@ logged in&quot;, log: OSLog.userFlow, type: .info, username)<br>}</pre><p>The Xcode console and the Console.app will show the data as normal when a debugger is attached.</p><pre>LogExample[7784:105423] [viewcycle] User shobhitlogged in<br>LogExample[7784:105423] [viewcycle] User shobhit logged in</pre><p>However, opening the app while no debugger is attached will show the following output in the Console.app.</p><pre>debug   18:58:40.532132 +0100   LogExample  User shobhit logged in<br>debug   18:58:40.532201 +0100   LogExample  User &lt;private&gt; logged in</pre><p>The username is logged as &lt;private&gt; instead which prevents your data from being readable by anyone inside the logs.</p><h3>Reading logs with the Console.app</h3><p>Using the Console.app in combination with OSLog is recommended to get the most out of this way of logging.</p><p>Start by selecting your device on the left in the devices menu. Simulators and connected devices will show up in this list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/0*oUpmMt7xu_h8Nnoz.png" /></figure><p>After selecting your device you can start entering a keyword in the search field, after which an option appears as <em>any</em> inside a drop-down menu.</p><p>This is the place in which you can filter on your category:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/0*pEmKsMibhz_Q12Gz.png" /></figure><p>We could go even further if this isn’t enough filtering by passing in the subsystem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*qfjb5wB_zke84PN3.png" /></figure><p>Make sure to include info and debug messages by enabling them from the action menu, so all your messages show up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/0*vLbdoUWJhqJmYV9a.png" /></figure><p>This should be enough to get you started with reading logs inside the Console.app.</p><h3>Improved APIs in iOS 14 and up</h3><p>WWDC 2020 introduced improved APIs that make it even easier to work with OSLog. The APIs look much more similar to popular frameworks like CocoaLumberjack and are better aligned with other Swift APIs.</p><p>All previous covered explanations in this blogpost still apply and the code examples are still working on iOS 14. However, if you’re supporting iOS 14 and up you might want to go with the improved APIs as they look nicer and come with a few new features.</p><h3>Using a Logger instance</h3><p>One of the differences is using the newly introduced Logger instance. The initialiser matches the one from OSLog:</p><pre>extension Logger {<br>    private static var subsystem = Bundle.main.bundleIdentifier!</pre><pre>    /// Logs the view cycles like viewDidLoad.<br>    static let viewCycle = Logger(subsystem: subsystem, category: &quot;viewcycle&quot;)<br>}</pre><p>The differences are visible when trying to log messages as you now have to use methods like info(_:) and debug(_:):</p><pre>Logger.viewCycle.info(&quot;View did load!&quot;)</pre><h3>Removed restriction of static strings</h3><p>A big improvements is the support for string interpolation and string literals. With the old API, it isn’t possible to use string interpolation which makes it harder to log values. With the new APIs you can log as you’re used to with print(_:)statements:</p><pre>Logger.viewCycle.debug(&quot;User \(username) logged in&quot;)</pre><h3>Setting the right privacy level</h3><p>When I used the old API it often happened that I forgot about the %{public}@syntax. In fact, I’ve been often writing it wrong with uppercase PUBLIC, for example.</p><p>With the new API we can make use of a better discoverable enum to set the right privacy level:</p><pre>Logger.viewCycle.debug(&quot;User \(username, privacy: .private) logged in&quot;)</pre><p>The string interpolation support is very useful here as we can decide the privacy level per logged value.</p><h3>Further reading</h3><p>WWDC often includes dedicated sessions to logging, including performance logging APIs. You can watch the sessions here:</p><ul><li><a href="https://developer.apple.com/videos/play/wwdc2018/405/">Measuring Performance </a><a href="https://developer.apple.com/videos/play/wwdc2018/405/">Using</a><a href="https://developer.apple.com/videos/play/wwdc2018/405/"> Logging</a> (WWDC 2018)</li><li><a href="https://developer.apple.com/videos/play/wwdc2020/10168/">Explore logging in Swift</a> (WWDC 2020)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea5ef8cb1c24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing High-Performance Swift Code- Part1]]></title>
            <link>https://shobhitgupta-27686.medium.com/writing-high-performance-swift-code-part1-a25749ef21ba?source=rss-596dececf765------2</link>
            <guid isPermaLink="false">https://medium.com/p/a25749ef21ba</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Shobhit Gupta]]></dc:creator>
            <pubDate>Tue, 27 Oct 2020 09:50:59 GMT</pubDate>
            <atom:updated>2020-10-27T09:50:59.351Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*zYO-PqfWb5gIv_EVll7OxA.png" /></figure><h4><em>whole module optimisation :-</em></h4><p>By default Swift compiles each file individually. This allows Xcode to compile multiple files in parallel very quickly. However, compiling each file separately prevents certain compiler optimizations. Swift can also compile the entire program as if it were one file and optimize the program as if it were a single compilation unit. This mode is enabled using the swiftc command line flag -whole-module-optimization. Programs that are compiled in this mode will most likely take longer to compile, but may run faster.</p><p>This mode can be enabled using the Xcode build setting ‘Whole Module Optimization’.</p><h4>Reducing Dynamic Dispatch:-</h4><p>swift is very versatile language in nature. it gives you the power to use direct dispatch, dynamic dispatch and static dispatch in one place.</p><p>Swift gives the programmer the ability to improve runtime performance when necessary by removing or reducing dynamism. This section goes through several examples of language constructs that can be used to perform such an operation.</p><p><em>Dynamic Dispatch :-</em></p><p>Classes use dynamic dispatch for methods and property accesses by default. Thus in the following code snippet, a.aProperty, a.doSomething() and a.doSomethingElse() will all be invoked via dynamic dispatch:</p><pre>class A {<br>  var aProperty: [Int]<br>  func doSomething() { ... }<br>  dynamic doSomethingElse() { ... }<br>}<br><br>class B: A {<br>  override var aProperty {<br>    get { ... }<br>    set { ... }<br>  }<br><br>  override func doSomething() { ... }<br>}<br><br>func usingAnA(_ a: A) {<br>  a.doSomething()<br>  a.aProperty = ...<br>}</pre><p>In Swift, dynamic dispatch defaults to indirect invocation through a vtable <a href="https://github.com/apple/swift/blob/main/docs/OptimizationTips.rst#id8">[1]</a>. If one attaches the dynamic keyword to the declaration, Swift will emit calls via Objective-C message send instead. In both cases this is slower than a direct function call because it prevents many compiler optimizations <a href="https://github.com/apple/swift/blob/main/docs/OptimizationTips.rst#id9">[2]</a> in addition to the overhead of performing the indirect call itself. In performance critical code, one often will want to restrict this dynamic behavior.</p><h3>Advice: Use ‘final’ when you know the declaration does not need to be overridden</h3><p>The final keyword is a restriction on a declaration of a class, a method, or a property such that the declaration cannot be overridden. This implies that the compiler can emit direct function calls instead of indirect calls. For instance in the following C.array1 and D.array1will be accessed directly <a href="https://github.com/apple/swift/blob/main/docs/OptimizationTips.rst#id10">[3]</a>. In contrast, D.array2 will be called via a vtable:</p><pre>final class C {<br>  // No declarations in class &#39;C&#39; can be overridden.<br>  var array1: [Int]<br>  func doSomething() { ... }<br>}<br><br>class D {<br>  final var array1: [Int] // &#39;array1&#39; cannot be overridden by a computed property.<br>  var array2: [Int]      // &#39;array2&#39; *can* be overridden by a computed property.<br>}<br><br>func usingC(_ c: C) {<br>   c.array1[i] = ... // Can directly access C.array without going through dynamic dispatch.<br>   c.doSomething() = ... // Can directly call C.doSomething without going through virtual dispatch.<br>}<br><br>func usingD(_ d: D) {<br>   d.array1[i] = ... // Can directly access D.array1 without going through dynamic dispatch.<br>   d.array2[i] = ... // Will access D.array2 through dynamic dispatch.<br>}</pre><h3>Advice: Use ‘private’ and ‘fileprivate’ when declaration does not need to be accessed outside of file</h3><p>Applying the private or fileprivate keywords to a declaration restricts the visibility of the declaration to the file in which it is declared. This allows the compiler to be able to ascertain all other potentially overriding declarations. Thus the absence of any such declarations enables the compiler to infer the final keyword automatically and remove indirect calls for methods and field accesses accordingly. For instance in the following, e.doSomething() and f.myPrivateVar, will be able to be accessed directly assuming E, F do not have any overriding declarations in the same file:</p><pre>private class E {<br>  func doSomething() { ... }<br>}<br><br>class F {<br>  fileprivate var myPrivateVar: Int<br>}<br><br>func usingE(_ e: E) {<br>  e.doSomething() // There is no sub class in the file that declares this class.<br>                  // The compiler can remove virtual calls to doSomething()<br>                  // and directly call E&#39;s doSomething method.<br>}<br><br>func usingF(_ f: F) -&gt; Int {<br>  return f.myPrivateVar<br>}</pre><h3>advice: if ‘wmo’ is enabled use internal when a declaration does not need to be accessed outside module.</h3><p>WMO (see section above) causes the compiler to compile a module’s sources all together at once. This allows the optimizer to have module wide visibility when compiling individual declarations. Since an internal declaration is not visible outside of the current module, the optimizer can then infer final by automatically discovering all potentially overridding declarations.</p><p>NOTE: Since in Swift the default access control level is internal anyways, by enabling Whole Module Optimization, one can gain additional devirtualization without any further work.</p><h3>using continer type effectively:-</h3><p>An important feature provided by the Swift standard library are the generic containers Array and Dictionary. This section will explain how to use these types in a performant manner.</p><h4>advice : use value types in array</h4><p>In Swift, types can be divided into two different categories: value types (structs, enums, tuples) and reference types (classes). A key distinction is that value types cannot be included inside an NSArray. Thus when using value types, the optimizer can remove most of the overhead in Array that is necessary to handle the possibility of the array being backed an NSArray.</p><p>Additionally, in contrast to reference types, value types only need reference counting if they contain, recursively, a reference type. By using value types without reference types, one can avoid additional retain, release traffic inside Array.</p><pre>// Don&#39;t use a class here.<br>struct PhonebookEntry {<br>  var name: String<br>  var number: [Int]<br>}<br><br>var a: [PhonebookEntry]</pre><p>Keep in mind that there is a trade-off between using large value types and using reference types. In certain cases, the overhead of copying and moving around large value types will outweigh the cost of removing the bridging and retain/release overhead.</p><h4>advice : Use ContiguousArray with reference types when NSArray bridging is unnecessary</h4><p>If you need an array of reference types and the array does not need to be bridged to NSArray, use ContiguousArray instead of Array:</p><pre>class C { ... }<br>var a: ContiguousArray&lt;C&gt; = [C(...), C(...), ..., C(...)]</pre><h4>Advice: Use inplace mutation instead of object-reassignment</h4><p>All standard library containers in Swift are value types that use COW (copy-on-write) <a href="https://github.com/apple/swift/blob/main/docs/OptimizationTips.rst#id11">[4]</a> to perform copies instead of explicit copies. In many cases this allows the compiler to elide unnecessary copies by retaining the container instead of performing a deep copy. This is done by only copying the underlying container if the reference count of the container is greater than 1 and the container is mutated. For instance in the following, no copying will occur when d is assigned to c, but when d undergoes structural mutation by appending 2, d will be copied and then 2 will be appended to d:</p><pre>var c: [Int] = [ ... ]<br>var d = c        // No copy will occur here.<br>d.append(2)      // A copy *does* occur here.</pre><p>Sometimes COW can introduce additional unexpected copies if the user is not careful. An example of this is attempting to perform mutation via object-reassignment in functions. In Swift, all parameters are passed in at +1, i.e. the parameters are retained before a callsite, and then are released at the end of the callee. This means that if one writes a function like the following:</p><pre>func append_one(_ a: [Int]) -&gt; [Int] {<br>  a.append(1)<br>  return a<br>}</pre><pre>var a = [1, 2, 3]<br>a = append_one(a)</pre><p>a may be copied <a href="https://github.com/apple/swift/blob/main/docs/OptimizationTips.rst#id12">[5]</a> despite the version of a without one appended to it has no uses after append_one due to the assignment. This can be avoided through the usage of inout parameters:</p><pre>func append_one_in_place(a: inout [Int]) {<br>  a.append(1)<br>}</pre><pre>var a = [1, 2, 3]<br>append_one_in_place(&amp;a)</pre><p>will continue this as it will be quite long if i include in single doc. There other important factors for performance while working with powerful tools like generics which i will cover in next([part2]) discussion.</p><p>Thanks in advance. Please give your support if you liked the content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a25749ef21ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Testing : The Right Way]]></title>
            <link>https://shobhitgupta-27686.medium.com/unit-testing-the-right-way-49574112040?source=rss-596dececf765------2</link>
            <guid isPermaLink="false">https://medium.com/p/49574112040</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Shobhit Gupta]]></dc:creator>
            <pubDate>Thu, 09 Jul 2020 14:37:15 GMT</pubDate>
            <atom:updated>2020-07-09T14:37:15.505Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unit Testing : The Right Way</h3><p><strong>What is Mock</strong> : <strong>Mock </strong>is used to describe dependencies that are not real in unit tests in order to isolate component and make sure it behaves as expected in all possible cases</p><p>In his book “<strong>xUnit test patterns</strong>”, <strong>Gerard Meszaros</strong> referred to those components as <strong>Test doubles</strong> . <strong>A test double</strong> can be any component we eventually use to satisfy an object dependencies.</p><p>Actually Mock is a part of <strong>test-doubles</strong>. While <strong>test-doubles </strong>are describes the whole family.</p><p>Components of test-doubles :-</p><ol><li>Dummy</li><li>Stub</li><li>Spy</li><li>Mock</li><li>Fake</li></ol><p><strong>Important terminology :</strong></p><p><strong><em>SUT : </em></strong><em>Stands for “System under test”, which refers to the component that the unit tests are about, For instance : the class we are testing .</em></p><h3>Dummy</h3><p>A dummy is a dependency that simply does not matter for the unit test. Usually it’s an object that will have no influence on the test results. It’s actually only used to fill the dependencies. Sometimes passing a null is way enough.</p><h4>We use a dummy to make the compiler stop crying about missing dependencies.</h4><p>A dummy also allows to clearly see objects and values that are (or not) used during a unit test.</p><p>Usually creating a dummy does not require a Framework or tool. since it’s only an empty implementation.</p><p>For example you have a dependency that you use to log events. This is something totally irrelevant to the test output. then we can use a dummy logger.</p><pre>// Logger interface definition<br>protocol Logger {<br>    func log(message: String)<br>}<br><br>// Logger real implementation<br>class PrintLogger: Logger {<br><br>    func log(message: String) {<br>        print(message)<br>    }<br>}<br><br>// Dummy logger will only sit there to fill the dependency<br>class DummyLogger: Logger {<br>    <br>    // Will do nothing.<br>    func log(message: String) {<br>        // Nothing ...<br>    }<br>}</pre><p>As a general rule, a dummy should do nothing. and return as close to nothing as possible.</p><h3>Stub</h3><p>This is probably the most common case of test doubles. A Stub provides predefined answers to indirect inputs the SUT will need during unit tests.</p><p>It can be created with a tool that will generate it based on the class type. Or it can be manually written as a set of hardcoded values that matches your test case.</p><p>We know we need a Stub when we need to control the indirect inputs of our SUT, While we don’t want to have any verification logic on it.</p><p>Here for example we need to create a test double for a user account manager dependency. which will return us some hardcoded values we will define depending on the test case.</p><pre>// The account manager dependency interface.<br>protocol AccountManager {<br>    var isUserAuthenticated: Bool { get }<br>}<br><br>class AccountManagerStub: AccountManager {<br>    <br>    // We implement the dependency property.<br>    var isUserAuthenticated = true<br>}</pre><h3>Spy</h3><p>A spy is a special type of test doubles, that remembers how and when it was called. It literally spies all the informations we can’t directly get from the SUT, which allows to capture indirect outputs.</p><p><em>Imp</em> : A Spy can also return some hardcoded values like Stubs, but with a the key difference. It does not perform any verification, it only gets indirect outputs out of the SUT so that we can verify them later.</p><p>Usually creating a spy does not require a framework or tool.</p><pre>protocol EMailService {<br>    func send(email: String)<br>}<br><br>class OrderController {<br><br>    let emailService: EMailService<br>    <br>    init(emailService: EMailService) {<br>        self.emailService = emailService<br>    }<br>    <br>    // Order product method will call a send method wich<br>    // returns nothing and, hence it will be dificult to test that sent was called.<br>    func order(product: String) {<br>        emailService.send(email: &quot;You orderd some \(product)&quot;)<br>    }<br>}<br><br>class EMailServiceSpy: EMailService {<br>    <br>    // In addition to the interface implementation.<br>    // The spy has some extra properties that<br>    // will remember how the dependency was called.<br>    var sendEmailCallCount: Int = 0<br>    <br>    func send(email: String) {<br>        sendEmailCallCount += sendEmailCallCount<br>    }<br>}</pre><p>Here for instance we have a sendEmail method which returns nothing, which is called inside OrderController.<br>How to make sure that sendEmail was called when testing OrderController? Knowing that sendEmail makes not output.</p><p>The answer is to create an EmailServiceSpy. which will record how many times sendEmail was called. so that we can use it as a test double when Testing OrderController.</p><h3>Mock</h3><p>Like a Spy, a Mock allows also to remember things about how it was called. but it has an extra feature which gives it it definition. <br>A mock knows what is the right behaviour. a mock knows what should take place.</p><p>In other words, a spy only gets out the values we need for our tests. A mock also verifies that those values matches what is expected.</p><p>Like stubs mocks might be created manually or generated using a tool.</p><p>Using the same example above here we used a mock with a verification method, that returns a boolean indicating whether send email was called the right number of time.</p><pre>protocol EMailService {<br>    func send(email: String)<br>}<br><br>class OrderController {<br><br>    let emailService: EMailService<br>    <br>    init(emailService: EMailService) {<br>        self.emailService = emailService<br>    }<br>    <br>    // Order product method will call a send method wich<br>    // returns nothing and, hence it will be dificult to test that sent was called.<br>    func order(product: String) {<br>        emailService.send(email: &quot;You orderd some \(product)&quot;)<br>    }<br>}<br><br>// A mock knows what is the right behavior that should take place.<br>class EMailServiceMock: EMailService {<br>    <br>    var sendEmailCallCount: Int = 0<br><br>    // It can do a part of the verification that used to be done only inside the test.<br>    func verifySendEmailWasCalled() -&gt; Bool {<br>        return sendEmailCallCount &gt; 0<br>    }<br>    <br>    func send(email: String) {<br>        sendEmailCallCount += sendEmailCallCount<br>    }<br>}</pre><p><strong>Question : </strong>Mock or Spy ?</p><p>It’s important to mention, as a general rule, a <strong>Mock should be the option to go for rather than Spies</strong>. we only use a spy when it’s not possible or complicated to use a mock. <br>Or for instance your code core needs some refactoring to be cleanly testable. then you can use spies.<br>Or let’s say you have a function callback as input for your SUT. and it’s not possible to mock it with the framework you are using.</p><h3>Fake</h3><p>A fake is a simplified implementation of a more complex dependency.<br>We usually use it when the SUT depends on another component which holds states.</p><p>A good candidate for a fake is a component that cannot be replaced with only static values. Hence <strong>a Fake should have some logic on </strong>it.</p><p>Let’s say you have a database dependency. obviously we will not be using a real database for our unit tests. then we can create a fake database that will store data in an array to simulated a database under unit tests</p><pre>class FakeUserDefaults: UserDefaults {<br><br>    // A dictionary we will use to store during uni tests<br>    private var fakeStorage: [String: Any] = [:]<br>    <br>    override func object(forKey defaultName: String) -&gt; Any? {<br>            return fakeStorage[defaultName]<br>    }<br>    <br>    // Override the real set method to fake user default behavior<br>    override func set(_ value: Any?, forKey defaultName: String) {<br>            fakeStorage[defaultName] = value<br>    }<br>}</pre><p>Note that a using a “OnMemory” database for unit tests is a kind of fakes also.</p><p>In the above example we did a FakeUserDefaults which is a subclass of the real UserDefaults , it overrides the <strong>set</strong> and <strong>objectForKey</strong> methods by using a dictionary to store and fetch values.</p><p>It’s important to note that a Fake logic can grow along with the real object. which may become complicated to maintain at a certain level. This is why it’s advised to use TDD while making fakes to keep them under control.</p><p>Thanks for Reading !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49574112040" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>