<?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 Rejaul Hasan on Medium]]></title>
        <description><![CDATA[Stories by Rejaul Hasan on Medium]]></description>
        <link>https://medium.com/@rejaul-hasan?source=rss-9ee5c35f2f32------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ckxa2G14fGfM5mEbVSTpFA.jpeg</url>
            <title>Stories by Rejaul Hasan on Medium</title>
            <link>https://medium.com/@rejaul-hasan?source=rss-9ee5c35f2f32------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:01:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rejaul-hasan/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[Why Floyd’s Tortoise and Hare Algorithm Work? Finding Starting node of a Cycle in a Linked List?]]></title>
            <link>https://rejaul-hasan.medium.com/why-floyds-tortoise-and-hare-algorithm-work-finding-starting-node-of-a-cycle-in-a-linked-list-50a66c1a150c?source=rss-9ee5c35f2f32------2</link>
            <guid isPermaLink="false">https://medium.com/p/50a66c1a150c</guid>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Rejaul Hasan]]></dc:creator>
            <pubDate>Sat, 20 May 2023 13:54:21 GMT</pubDate>
            <atom:updated>2023-05-20T13:54:21.638Z</atom:updated>
            <content:encoded><![CDATA[<p>The algorithm instruction said</p><ol><li>We need to find the 1st intersection point of fast and slow pointer.</li><li>Now start a new pointer from intersection point and another pointer from the beginning.</li><li>When they meet each other that will be our cycle starting point.</li></ol><p>Let’s see the problem below. We need to find the starting node of the cycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*-LBhlC-bxvIfmq1BW4UeHQ.png" /></figure><blockquote>Let’s prove it:</blockquote><p>After 4 iteration our slow pointer should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*xeRBU8Pf4bP5whdK_1N92Q.png" /></figure><p>After 4 iteration our fast pointer should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*fpxt1ymOggS2vVaudnAaow.png" /></figure><p>Now consider before starting cycle we have to go <strong>x</strong> length. The cycle length is <strong>c</strong>. And distance from 2 pointer intersection point to cycle starting point is <strong>p</strong>. Then we can say.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*KTmfDmeZJMdGs_5Zig6MlA.png" /></figure><p><strong>2 * slow pointer travel distance = fast pointer travel distance</strong></p><blockquote>Let’s find slow pointer and fast pointer travel distance when intersection each other(red node)</blockquote><p><strong>slow pointer travel distance = X+(C-P)</strong></p><p><strong>fast pointer travel distance = X + C + (C-P)</strong></p><blockquote>we can say</blockquote><p><strong>2(X+(C-P)) = X+C+ C -P</strong></p><p><strong>2X+2C-2P — X — 2C + P = 0</strong></p><p><strong>X — P = 0</strong></p><p><strong>X = P</strong></p><p>So, it’s prove.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50a66c1a150c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Common STL]]></title>
            <link>https://rejaul-hasan.medium.com/common-stl-8c4ec19dfc08?source=rss-9ee5c35f2f32------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c4ec19dfc08</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[stl]]></category>
            <dc:creator><![CDATA[Rejaul Hasan]]></dc:creator>
            <pubDate>Thu, 18 May 2023 15:48:23 GMT</pubDate>
            <atom:updated>2023-05-18T15:48:23.564Z</atom:updated>
            <content:encoded><![CDATA[<p>This is an overview of c++ STL.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3aea1f4ed099a623eb476bcbf4ef37a9/href">https://medium.com/media/3aea1f4ed099a623eb476bcbf4ef37a9/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c4ec19dfc08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualize iOS App’s Dependency Graph]]></title>
            <link>https://rejaul-hasan.medium.com/visualize-ios-apps-dependency-graph-abe45098d913?source=rss-9ee5c35f2f32------2</link>
            <guid isPermaLink="false">https://medium.com/p/abe45098d913</guid>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[memory-improvement]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Rejaul Hasan]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 10:18:03 GMT</pubDate>
            <atom:updated>2023-04-02T10:18:29.793Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understand what’s going on with your project</h4><p>It’s really important for a developer to understand what’s the dependencies among the objects in a project. Without analysing it properly, it often happens that you introduce some memory leak and you don’t even aware of it.</p><p>Xcode provide <strong>debug memory graph</strong> to simulate run time objects in our memory and there dependencies. It’s a great tool to analyse.</p><p>There also have some 3rd party tools which quite helpful to understand, visualize the run time objects and there dependencies. One of them is</p><p><a href="https://github.com/PaulTaykalo/objc-dependency-visualizer"><strong>Objective-C And Swift Dependencies Visualizer</strong></a></p><p>let’s use it.</p><p>clone the repo using below cmd and go to the directory.</p><pre>git clone https://github.com/PaulTaykalo/objc-dependency-visualizer.git</pre><p>now run your project in xcode. Then execute the below cmd in terminal.</p><pre>./generate-objc-dependencies-to-json.rb -d -s &quot;&quot; -p /path/to/YourProject&gt; origin.js ;</pre><p>It will take your project from driver data and write your projects object dependency graph into index.html. So in <strong>/path/to/YourProject </strong>must give your project <strong>driver data location</strong>. Now open the index.html.</p><pre>open index.html</pre><p>it will show something like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NtViECUEI4TPIKqvZ5Zhhw.png" /></figure><p>Here you can saw the all classes and there relationship.</p><p>If you click a single class you are able to saw it’s dependencies very well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZFbPjGQMPnpy2R5sn4PdXg.png" /></figure><p>Here I click <strong>CurrencyExchangeViewModel</strong> class.</p><p><strong>What about that you want to analyse only one class and it’s dependencies?</strong></p><p>yes, it possible using this cmd. Here MyClass is your target class.</p><pre>./generate-objc-dependencies-to-json.rb -s &quot;MyClass&quot; -p /path/to/MyProject &gt; origin.js</pre><p><strong>What about you want to exclude one class from the analysis?</strong></p><p>Yes, you can using below cmd. Here all the classes start with <strong>Private_</strong> will exclude.</p><pre>./generate-objc-dependencies-to-json.rb -s &quot;&quot; -p /path/to/MyProject -e &quot;Private_*&quot; &gt; origin.js</pre><p>You can also change the colour code according to you types by editing below code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c88b2Ww3DVvpKo5MQQKQkw.png" /></figure><h4>Resources:</h4><ol><li><a href="https://github.com/PaulTaykalo/objc-dependency-visualizer">https://github.com/PaulTaykalo/objc-dependency-visualizer</a></li><li><a href="https://chat.openai.com/chat">chat.openai.com</a></li></ol><p>Those who follow or read comment down if you have questions. <strong>If you want to connect, knock me on </strong><a href="https://www.linkedin.com/in/md-rejaul-hasan-0a5a11131/"><strong>LinkedIn</strong></a>. Happy coding and stay safe.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abe45098d913" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Combine Framework- Part 6]]></title>
            <link>https://rejaul-hasan.medium.com/combine-framework-part-6-26d0c99fa409?source=rss-9ee5c35f2f32------2</link>
            <guid isPermaLink="false">https://medium.com/p/26d0c99fa409</guid>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Rejaul Hasan]]></dc:creator>
            <pubDate>Sun, 03 Jul 2022 07:52:21 GMT</pubDate>
            <atom:updated>2022-07-03T07:52:21.390Z</atom:updated>
            <content:encoded><![CDATA[<h4>Error Handling, Schedulers</h4><h3>Error Handling</h3><blockquote><strong>Convert an infallible object into a failure type</strong></blockquote><p>A publisher whose Failure is of type Never indicates that the publisher can <strong>never fail</strong>. Let’s make them failable.</p><p><strong>setFailureType</strong></p><p>The first way to turn an infallible publisher into a fallible one is to use setFailureType. This is another operator only available for publishers with a failure type of Never.</p><pre><strong>enum</strong> MyError: Error {<br><strong>case</strong> ohNo<br>}</pre><pre>example(of: &quot;setFailureType&quot;) {<br>Just(&quot;Hello&quot;)<br>.setFailureType(to: MyError.<strong>self</strong>)<br>.sink { completion <strong>in<br>switch</strong> completion{<br><strong>case</strong> .failure(.ohNo):<br>print(&quot;Finished with Oh No!&quot;)<br><strong>case</strong> .finished:<br>print(&quot;Finished successfully!&quot;)<br>}<br>} receiveValue: { value <strong>in<br></strong>print(&quot;got value \(value)&quot;)<br>}.store(in: &amp;subscriptions)<br>}</pre><p>Here <strong>just</strong> is a non-fail-able publisher and you change the error type into <strong>MyError</strong> by using the <strong>setFailureType(to: MyError.self) </strong>operator.</p><p><strong>assign(to:on:)</strong></p><p>only works on publishers that cannot fail. So, you are not permitted to use <strong>setFailureType(to: MyError.self) </strong>operator here. It will give you an error. Simple example.</p><pre><strong>class</strong> Person {<br><strong>let</strong> id = UUID()<br><strong>var</strong> name = &quot;Unknown&quot;<br>}</pre><pre><strong>let</strong> person = Person()<br>print(&quot;1&quot;, person.name)<br>Just(&quot;Shai&quot;)<br>.handleEvents(<br>receiveCompletion: { _ <strong>in</strong> print(&quot;2&quot;, person.name) }<br>).assign(to: \.name, on: person)<br>.store(<strong>in</strong>: &amp;subscriptions)</pre><pre><strong>//Output </strong><br><strong>1 Unknown<br>2 Shai</strong></pre><p><strong>assertNoFailure</strong></p><p>The assertNoFailure operator is useful when you want to protect yourself during development and confirm a publisher can’t finish with a failure event. It doesn’t <em>prevent </em>a failure event from being emitted by the upstream. However, it will crash with a fatalError if it detects an error, which gives you a good incentive to fix it in development.</p><pre><strong>enum</strong> MyError: Error {<br><strong>case</strong> ohNo<br>}</pre><pre>Just(&quot;Hello&quot;)<br>.setFailureType(to: MyError.<strong>self</strong>)<br>.tryMap({ _ <strong>in<br>throw</strong> MyError.ohNo<br>}).assertNoFailure()<br>.sink(receiveValue: { print(&quot;Got value: \($0) &quot;)})<br>.store(<strong>in</strong>: &amp;subscriptions)</pre><p>It will crash immediately as <strong>tryMap</strong> throw an error and <strong>.assertNoFailure()</strong> crash with <strong>fatalError</strong> when it get an error from upstream.</p><blockquote><strong>Dealing with failure</strong></blockquote><p><strong>try* operators</strong></p><pre><strong>enum</strong> NameError: Error{<br><strong>case</strong> tooShort(String)<br><strong>case</strong> unknown<br>}</pre><pre>Just(&quot;Hello&quot;)<br>.setFailureType(to: NameError.<strong>self</strong>)<br>.tryMap {<br>$0.count<br>}.sink { completion <strong>in<br>switch</strong> completion{<br><strong>case</strong> .finished:<br>print(&quot;finish&quot;)<br><strong>case</strong> .failure(<strong>let</strong> err):<br>print(err.localizedDescription)<br>}<br>} receiveValue: { value <strong>in<br></strong>print(value)<br>}.store(in: &amp;subscriptions)</pre><p>Here, we use <strong>setFailureType</strong> and set <strong>NameError</strong> as our error type but notice inside our .<strong>sink</strong> completion block, we use <strong>Switch</strong> statement where try to match with normal <strong>Error</strong> type not our specific <strong>NameError</strong> type. Why it happen?</p><p>Very interesting! <strong>tryMap</strong> erased your strictly-typed error and replaced it with a general <strong>Swift.Error</strong> type. This happens even though you didn’t actually throw an error from within <strong>tryMap</strong> — you simply used it! So, how do we handle this problem? and throw our specific type error.</p><pre>[&quot;new test&quot;, &quot;test&quot;]<br>.publisher<br>.setFailureType(to: NameError.<strong>self</strong>)<br>.tryMap {<br><strong>if</strong>($0.count &gt; 5){<br><strong>return</strong> $0.count<br>}<strong>else</strong>{<br><strong>throw</strong> NameError.tooShort($0)<br>}<br>}.mapError { $0 <strong>as</strong>? NameError ?? .unknown }<br>.sink { completion <strong>in<br>switch</strong> completion{<br><strong>case</strong> .finished:<br>print(&quot;finish&quot;)<br><strong>case</strong> .failure(NameError.unknown):<br>print(&quot;Unknown&quot;)<br><strong>case</strong> .failure(NameError.tooShort(<strong>let</strong> name)):<br>print(&quot;\(name) is too short!&quot;)<br>}<br>} receiveValue: { value <strong>in<br></strong>print(value)<br>}.store(in: &amp;subscriptions)</pre><pre><strong>//Output </strong><br><strong>8<br>test is too short!</strong></pre><p>So <strong>.mapError { $0 as? NameError ?? .unknown }</strong> cast our <strong>swift.error</strong> type back in our custom error type <strong>NameError </strong>and we can use them inside our subscriber.</p><p><strong>Designing your fallible APIs</strong></p><p>When constructing your own Combine-based code and APIs, you’ll often use APIs from other sources that return publishers that fail with various types. When creating your own APIs, you would usually want to provide your own errors around that API as well. Let’s see an example.</p><pre><strong>class</strong> DadJokes {</pre><pre><strong>struct</strong> Joke: Codable {<br><strong>let</strong> id: String<br><strong>let</strong> joke: String<br>}</pre><pre><strong>enum</strong> Error: Swift.Error, CustomStringConvertible {<br><strong>case</strong> network<br><strong>case</strong> jokeDoesntExist(id: String)<br><strong>case</strong> parsing<br><strong>case</strong> unknown</pre><pre><strong>var</strong> description: String {<br><strong>switch</strong> <strong>self</strong> {<br><strong>case</strong> .network:<br><strong>return</strong> &quot;Request to API Server failed&quot;<br><strong>case</strong> .parsing:<br><strong>return</strong> &quot;Failed parsing response from server&quot;<br><strong>case</strong> .jokeDoesntExist(<strong>let</strong> id):<br><strong>return</strong> &quot;Joke with ID \(id) doesn&#39;t exist&quot;<br><strong>case</strong> .unknown:<br><strong>return</strong> &quot;An unknown error occurred&quot;<br>}<br>}<br>}</pre><pre><strong>func</strong> getJoke(id: String)-&gt; AnyPublisher&lt;Joke,Error&gt;{<br><strong>guard</strong> id.rangeOfCharacter(from: .letters) != <strong>nil</strong> <strong>else</strong> {<br><strong>return</strong> Fail&lt;Joke, Error&gt;(error: .jokeDoesntExist(id: id))<br>.eraseToAnyPublisher()<br>}</pre><pre><strong>let</strong> url = URL(string: &quot;https://icanhazdadjoke.com/j/\(id)&quot;)!<br><strong>var</strong> request = URLRequest(url: url)<br>request.allHTTPHeaderFields = [&quot;Accept&quot;: &quot;application/json&quot;]<br><strong>return</strong> URLSession.shared.dataTaskPublisher(for: request)<br>.tryMap({ data, _ <strong>in<br>guard</strong> <strong>let</strong> obj = <strong>try</strong>? JSONSerialization.jsonObject(with: data),<br><strong>let</strong> dict = obj <strong>as</strong>? [String: <strong>Any</strong>],<br>dict[&quot;status&quot;] <strong>as</strong>? Int == 404 <strong>else</strong> {<br><strong>return</strong> data<br>}<br><strong>throw</strong> DadJokes.Error.jokeDoesntExist(id: id)<br>})<br>.decode(type: Joke.<strong>self</strong>, decoder: JSONDecoder())<br>.mapError({ error <strong>in<br>switch</strong> error{<br><strong>case</strong> <strong>is</strong> URLError:<br><strong>return</strong> .network<br><strong>case</strong> <strong>is</strong> DecodingError:<br><strong>return</strong> .parsing<br><strong>default</strong>:<br><strong>return</strong> error <strong>as</strong>? DadJokes.Error ?? .unknown<br>}<br>})<br>.eraseToAnyPublisher()<br>}<br>}</pre><p>Here, we have a <strong>DadJokes</strong> class which responsibility is to do a network call and parse the json to our expected struct name <strong>Joke</strong>. If it fail we try to throw a proper custom error name <strong>Error</strong> so that we can handle it letter. So let’s call it or use it.</p><pre><strong>let</strong> api = DadJokes()<br><strong>let</strong> jokeID = &quot;9prWnjyImyd&quot;<br><strong>let</strong> badJokeID = &quot;123456&quot;</pre><pre>api<br>.getJoke(id: jokeID)<br>.sink(receiveCompletion: { print($0) },<br>receiveValue: { print(&quot;Got joke: \($0)&quot;) })<br>.store(in: &amp;subscriptions)</pre><p><strong>Catching and retrying</strong></p><p><strong>.retry()</strong></p><p>The retry operator accepts a number. If the publisher fails, it will resubscribe to the upstream and <em>retry </em>up to the number of times you specify. If all retries fail, it simply pushes the error downstream as it would without the retry operator. Let’s see an example.</p><p>Here assume we have a class name <strong>PhotoService</strong> which provide a function name <strong>fetchPhoto</strong> that give us a publisher. In parameter of <strong>fetchPhoto function </strong>we can define the image quality we need. Here, we asking for <strong>high</strong> quality image which normally fail and then we retry 2 more times to fetch it.</p><pre><strong>let</strong> photoService = PhotoService()</pre><pre>photoService<br>.fetchPhoto(quality: .high)<br>.handleEvents(<br>receiveSubscription: { _ <strong>in</strong> print(&quot;Trying ...&quot;) },<br>receiveCompletion: {<br><strong>guard</strong> <strong>case</strong> .failure(<strong>let</strong> error) = $0 <strong>else</strong> { <strong>return</strong> }<br>print(&quot;Got error: \(error)&quot;)<br>}<br>)<br>.retry(2)<br>.sink {<br>print(&quot;\($0)&quot;)<br>} receiveValue: { image <strong>in<br></strong>image<br>print(&quot;Got image: \(image)&quot;)<br>}<br>.store(in: &amp;subscriptions)</pre><pre>// Output is <br><strong>Trying ...<br>Got error: Failed fetching image with high quality<br>Trying ...<br>Got error: Failed fetching image with high quality<br>Trying ...<br>Got error: Failed fetching image with high quality<br>failure(Failed fetching image with high quality)</strong></pre><p>As you can see, there are 3 attempts. The initial attempt, plus 2 retries triggered by the retry operator. Because fetching a high-quality photo constantly fails, the operator exhausts all its retry attempts and pushes the error down to sink.</p><p>As here we try to fetch high quality image and it fail all the time maybe for low internet connection. So, what should we do in that case? We should try to fetch low quality image instead of high quality image. If low quality also fail then we should pass a local dummy image. So, our user will not feel blank.</p><p><strong>.replaceError()</strong></p><p>Let’s give a dummy local image first</p><pre><strong>let</strong> photoService = PhotoService()</pre><pre>photoService<br>.fetchPhoto(quality: .high)<br>.handleEvents(<br>receiveSubscription: { _ <strong>in</strong> print(&quot;Trying ...&quot;) },<br>receiveCompletion: {<br><strong>guard</strong> <strong>case</strong> .failure(<strong>let</strong> error) = $0 <strong>else</strong> { <strong>return</strong> }<br>print(&quot;Got error: \(error)&quot;)<br>}<br>)<br>.retry(1)<br>.replaceError(with: UIImage(named: &quot;na.jpg&quot;)!)<br>.sink {<br>print(&quot;\($0)&quot;)<br>} receiveValue: { image <strong>in<br></strong>image<br>print(&quot;Got image: \(image)&quot;)<br>}<br>.store(in: &amp;subscriptions)</pre><pre>// Output is <br><strong>Trying ...<br>Got error: Failed fetching image with high quality<br>Trying ...<br>Got error: Failed fetching image with high quality<br>Got image: &lt;UIImage:0x6000012f5440 named(na.jpg) {200, 200} renderingMode=automatic&gt;<br>finished</strong></pre><p>So, here it tries to fetch the image 2 times and when it fails it will replace the error with a dummy image by calling <strong>.replaceError(with: UIImage(named: “na.jpg”)!).</strong></p><p><strong>.catch()</strong></p><p>Now, let’s do the another part. If high quality image download fail, we will fall down into low quality image download and try to fetch it.</p><p><strong>Combine provides the perfect operator for this task, called catch. It lets you <em>catch </em>a failure from a publisher and recover from it with a different publisher.</strong></p><p><strong>Apple doc about catch:- </strong>Handles errors from an upstream publisher by replacing it with another publisher.</p><pre><strong>let</strong> photoService = PhotoService()</pre><pre>photoService<br>.fetchPhoto(quality: .high)<br>.handleEvents(<br>receiveSubscription: { _ <strong>in</strong> print(&quot;Trying ...&quot;) },<br>receiveCompletion: {<br><strong>guard</strong> <strong>case</strong> .failure(<strong>let</strong> error) = $0 <strong>else</strong> { <strong>return</strong> }<br>print(&quot;Got error: \(error)&quot;)<br>}<br>)<br>.retry(1)<br>.catch({ _ -&gt; PhotoService.Publisher <strong>in<br></strong>print(&quot;Failed fetching high quality, falling back to low quality&quot;)<br><strong>return</strong> photoService.fetchPhoto(quality: .low)<br>})<br>.replaceError(with: UIImage(named: &quot;na.jpg&quot;)!)<br>.sink {<br>print(&quot;\($0)&quot;)<br>} receiveValue: { image <strong>in<br></strong>image<br>print(&quot;Got image: \(image)&quot;)<br>}<br>.store(in: &amp;subscriptions)</pre><h3>Schedulers</h3><p>Some operator we use scheduler as a parameter. Let’s have a look at them. Part-5 also describe them.</p><pre>• debounce(for:scheduler:options:)<br>• delay(for:tolerance:scheduler:options:)<br>• measureInterval(using:options:)<br>• throttle(for:scheduler:latest:)<br>• timeout(_:scheduler:options:customError:)</pre><p><strong>subscribe(on:):</strong></p><p>Without subscription it will work on current thread. Here it is main thread.</p><pre>let subscription = computationPublisher<br>  .sink { value in<br>    let thread = Thread.current.number<br>    print(&quot;Received computation result on thread \(thread): &#39;\<br>(value)&#39;&quot;)<br>}</pre><p>Now let’s subscribe</p><pre>let subscription = computationPublisher<br>  .subscribe(on: queue)<br>  .sink { value in<br>     let thread = Thread.current.number<br>     print(&quot;Received computation result on thread \(thread): &#39;\<br>(value)&#39;&quot;)<br>}</pre><p>the execution will be like below</p><pre>Start computation publisher on thread 1<br>ExpensiveComputation subscriber received on thread 5<br>Beginning expensive computation from thread 5<br>Completed expensive computation on thread 5<br>Received computation result on thread 5 &#39;Computation complete&#39;</pre><p>But what if you wanted to update some on-screen info? You would need to do something like DispatchQueue.main.async { … } in your sink closure, just to make sure you’re performing UI updates from the main thread.</p><p>There is a more effective way to do this with Combine!</p><p><strong>receive(on:):</strong></p><p>It lets you specify which scheduler should be used to deliver values to subscribers.</p><pre>let subscription = computationPublisher<br>  .subscribe(on: queue)<br>  .receive(on: DispatchQueue.main)<br>  .sink { value in</pre><p>the execution will be like below</p><pre>Start computation publisher on thread 1<br>ExpensiveComputation subscriber received on thread 4<br>Beginning expensive computation from thread 4<br>Completed expensive computation on thread 4<br>Received computation result on thread 1 &#39;Computation complete&#39;</pre><p><strong>Scheduler implementations</strong></p><p>Apple provides several concrete implementations of the Scheduler protocol:</p><ul><li><strong>ImmediateScheduler</strong>: A simple scheduler that executes code immediately on the current thread, which is the default execution context unless modified using subscribe(on:), receive(on:) or any of the other operators which take a scheduler as parameter.</li><li><strong>RunLoop</strong>: Tied to Foundation’s Thread object.</li><li><strong>DispatchQueue</strong>: Can either be serial or concurrent.</li><li><strong>OperationQueue</strong>: A queue that regulates the execution of work items.</li></ul><p><strong>ImmediateScheduler</strong>:</p><p>A simple scheduler that executes code immediately on the current thread.</p><p><strong>ImmediateScheduler options:</strong></p><p>With most of the operators accepting a Scheduler in their arguments, you can also find an options argument which accepts a SchedulerOptions value. In the case of ImmediateScheduler, this type is defined as Never so when using ImmediateScheduler, you should never pass a value for the options parameter of the operator.</p><p><strong>RunLoop scheduler</strong></p><p>Predating DispatchQueue, it is a way to manage input sources at the thread level, including in the Main (UI) thread. Your application’s main thread still has an associated RunLoop. You can also obtain one for any Foundation Thread by calling RunLoop.current from the current thread.</p><pre>let source = Timer<br>  .publish(every: 1.0, on: .main, in: .common)<br>  .autoconnect()<br>  .scan(0) { (counter, _) in counter + 1 }</pre><pre>let setupPublisher = { recorder in<br>  source<br>    .receive(on: DispatchQueue.global())<br>    .recordThread(using: recorder)<br>    .receive(on: RunLoop.current)<br>    .recordThread(using: recorder)<br>    .eraseToAnyPublisher()<br>}<br>let view = ThreadRecorderView(title: &quot;Using RunLoop&quot;, setup:<br>setupPublisher)<br>PlaygroundPage.current.liveView = UIHostingController(rootView:<br>view)</pre><p>But what is <strong>RunLoop.current?</strong> It is the <em>RunLoop associated with the thread that was current when the call was made</em>. The closure is being called by <strong>ThreadRecorderView</strong>, from the main thread to set up the publisher and the recorder. Therefore, <strong>RunLoop.current</strong> is the main thread’s RunLoop.</p><p>The output is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*px9enhMXFaHnP6Gj1e4Ptw.png" /></figure><p>As requested, the first recordThread shows that each value goes through one of the global concurrent queue’s threads, then continues on the main thread.</p><p><strong>A little comprehension challenge</strong></p><p>What would happen if you had used subscribe(on: DispatchQueue.global()) instead of receive(on:) the first time? Try it!</p><p>You see that everything is recorded on thread one. It may not be obvious at first, but it is entirely logical. Yes, the publisher was subscribed to on the concurrent queue. But remember that you are using a Timer which is emitting its values… on the main RunLoop! Therefore, regardless of the scheduler you pick to subscribe to this publisher on, values will always begin their journey on the main thread.</p><p><strong>Scheduling code execution with RunLoop</strong></p><pre>RunLoop.current.schedule(after: .init(Date(timeIntervalSinceNow: 4.5)), tolerance: .milliseconds(500)) {<br>// you action code<br>threadRecorder?.subscription?.cancel()<br>}</pre><p><strong>RunLoop pitfalls</strong></p><p>Usages of RunLoop should be restricted to the main thread’s run loop, and to the RunLoop available in Foundation threads that you control if needed. That is, anything you started yourself using a Thread object.</p><p>One particular pitfall to avoid is using RunLoop.current in code executing on a DispatchQueue. This is because DispatchQueue threads can be ephemeral, which makes them nearly impossible to rely on with RunLoop.</p><p><strong>DispatchQueue scheduler</strong></p><p>The Dispatch framework is a powerful component of Foundation that allows you to <em>execute code concurrently on multicore hardware by submitting work to dispatch queues managed by the system</em>.</p><p><strong>Queues and threads</strong></p><p>Meaning you should never make any assumption about the current thread in code that runs in a queue. In particular, you should not schedule work using RunLoop.current because of the way DispatchQueue manages its threads.</p><p>This is an important distinction: When using subscribe(on:), receive(on:) or any of the other operators taking a Scheduler parameter, you should never assume that the thread backing the scheduler is the same every time.</p><p><strong>Using DispatchQueue as a scheduler</strong></p><pre>let serialQueue = DispatchQueue(label: &quot;Serial queue&quot;)<br>let sourceQueue = DispatchQueue.main</pre><pre>let source = PassthroughSubject&lt;Void, Never&gt;()<br>let subscription = sourceQueue.schedule(after: sourceQueue.now, interval: .seconds(1)){<br>    source.send()<br>}</pre><pre>let setupPublisher = { recorder in<br>    source<br>        .recordThread(using: recorder)<br>        .receive(on: serialQueue)<br>        .recordThread(using: recorder)<br>        .eraseToAnyPublisher()<br>}</pre><pre>let view = ThreadRecorderView(title: &quot;Using DispatchQueue&quot;,setup: setupPublisher)<br>PlaygroundPage.current.liveView = UIHostingController(rootView:view)</pre><p>the output is like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*V-ib77m-gjFHldE2XzFsrA.png" /></figure><p>Did you notice how the second recordThread(using:) records changes in the current thread after the receive(on:) operator? This is a perfect example of how DispatchQueue makes no guarantee over which thread each work item executes on. In the case of receive(on:), a <strong>work item </strong>is a value that hops from the current scheduler to another.</p><p><strong>DispatchQueue options</strong></p><pre>.receive(<br>  on: serialQueue,options: DispatchQueue.SchedulerOptions(qos: .userInteractive)<br>)</pre><p>All options are given <a href="https://developer.apple.com/documentation/dispatch/dispatchqos">here</a>.</p><p><strong>OperationQueue</strong></p><p>This system class is defined as <em>a queue that regulates the execution of operations</em>. It is a rich regulation mechanism that lets you create advanced operations with dependencies. But in the context of Combine, you will use none of these mechanisms.</p><pre>let queue = OperationQueue()<br>let subscription = (1...10).publisher<br>  .receive(on: queue)<br>  .sink { value in<br>print(&quot;Received \(value)&quot;)<br>  }</pre><p>the output is</p><pre>Received 4<br>Received 3<br>Received 2<br>Received 7<br>Received 5<br>Received 10<br>Received 6<br>Received 9<br>Received 1<br>Received 8</pre><p>It’s <strong>maxConcurrentOperationCount</strong>. It defaults to a system-defined number that allows an operation queue to execute a large number of operations concurrently. Since your publisher emits all its items at roughly the same time, they get dispatched to multiple threads by Dispatch’s concurrent queues!</p><p><strong>OperationQueue pitfalls</strong></p><p>You just saw that OperationQueue executes operations concurrently by default. You need to be very aware of this as it can cause you trouble: By default, an OperationQueue behaves like a <em>concurrent </em>DispatchQueue.</p><p>It can be a good tool, though, when you have significant work to perform every time a publisher emits a value. You can control the load by tuning themaxConcurrentOperationCount parameter.</p><p>Those who follow or read comment down if you have questions. I am planning to write on testing from <a href="https://www.amazon.com/iOS-Unit-Testing-Example-Techniques/dp/1680506811"><strong>iOS Unit Testing by Example</strong></a><strong> and also review </strong><a href="https://www.amazon.com/Head-First-Design-Patterns-Brain-Friendly/dp/0596007124"><strong>Head First Design Patterns</strong></a>. Those are very core books. Everyone should use those as reference books. I also love to write more <strong>algorithm</strong> topics soon. So stay positive and we will learn many things together. <strong>If you want to connect, knock me on </strong><a href="https://www.linkedin.com/in/md-rejaul-hasan-0a5a11131/"><strong>LinkedIn</strong></a>. Happy coding and stay safe.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26d0c99fa409" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Combine Framework-Part 5]]></title>
            <link>https://rejaul-hasan.medium.com/combine-framework-part-5-493acc67e528?source=rss-9ee5c35f2f32------2</link>
            <guid isPermaLink="false">https://medium.com/p/493acc67e528</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[combine]]></category>
            <dc:creator><![CDATA[Rejaul Hasan]]></dc:creator>
            <pubDate>Thu, 30 Jun 2022 11:51:13 GMT</pubDate>
            <atom:updated>2022-06-30T11:51:13.522Z</atom:updated>
            <content:encoded><![CDATA[<h4>Time Manipulation Operators</h4><p><strong>Shifting time</strong></p><p>The delay(for:tolerance:scheduler:options) operator time-shifts a whole sequence of values: Every time the upstream publisher emits a value, delay keeps it for a while then emits it after the delay you asked for, on the Scheduler you specified.</p><pre><strong>let</strong> valuesPerSecond = 1.0<br><strong>let</strong> delayInSeconds = 1.5<br><strong>let</strong> sourcePublisher = PassthroughSubject&lt;Date,Never&gt;()<br><strong>let</strong> delayedPublisher = sourcePublisher.delay(for: .seconds(delayInSeconds), scheduler: DispatchQueue.main)<br><strong>let</strong> subscription = Timer.publish(every: valuesPerSecond, on: .main, in: .common).autoconnect().subscribe(sourcePublisher)</pre><p>Here, <strong>Timer</strong> publish <strong>date</strong> every second and <strong>sourcePublisher</strong> with the help of <strong>delay</strong> operator makes it delay 1.5 seconds.</p><p><strong>Collecting values</strong></p><p>In certain situations, you may need to collect values emitted by a publisher at specified intervals. This is a form of buffering that can be useful. For example, when you want to average a group of values over short periods of time and output the average.</p><pre><strong>let</strong> valuesPerSecond = 1.0<br><strong>let</strong> collectTimeStride = 4</pre><pre><strong>let</strong> sourcePublisher = PassthroughSubject&lt;Date, Never&gt;()<br><strong>let</strong> collectedPublisher = sourcePublisher.collect(.byTime(DispatchQueue.main, .seconds(collectTimeStride))).sink { _ <strong>in<br></strong>//<br>} receiveValue: { d <strong>in<br></strong>print(d)<br>}</pre><pre><strong>let</strong> subscription = Timer.publish(every: valuesPerSecond, on: .main, in: .common).autoconnect().subscribe(sourcePublisher)</pre><p>So, it store’s all the data emmited by timer within 4 seconds in an array and then pass it in downstream.</p><p><strong>Collecting values (part 2)</strong></p><p>The second option offered by the collect(_:options:) operator allows you to keep collecting values at regular intervals. It also allows you to limit the number of collected values.</p><pre>collect(.byTimeOrCount(DispatchQueue.main, .seconds(collectTimeStride), collectMaxCount))</pre><p>This will collect up to <strong>collectMaxCount</strong> values at a time. So, if <strong>collectMaxCount = 2</strong> and <strong>collectTimeStride = 4</strong>, then it will collect first 2 value within 4 second. Rest will collect latter.</p><h3>Debounce</h3><p>Publishes elements only after a specified time interval elapses between events.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39bc5f805ded1b851b311d30dc0fa885/href">https://medium.com/media/39bc5f805ded1b851b311d30dc0fa885/href</a></iframe><p>N.B:- One thing to watch out for is the publisher’s completion. If your publisher completes right after the last value was emitted, but before the time configured for debounce elapses, you will never see the last value in the debounced publisher!</p><p><strong>Throttle</strong></p><pre>let throttleDelay = 1.0<br>let subject = PassthroughSubject&lt;String, Never&gt;()<br>let throttled = subject<br>  .throttle(for: .seconds(throttleDelay), scheduler:DispatchQueue.main, latest: false).share()</pre><ol><li>The source publisher will emit strings.</li><li>Your throttled subject will now only emit the first value received from subject during each one-second interval because you set latest to false.</li><li>Like in the previous operator, debounce, adding the share() operator here guarantees that all subscribers see the same output at the same time from the throttled subject.</li></ol><p><strong>There you have the fundamental difference between debounce and throttle:</strong></p><ul><li>debounce waits for a pause in values it receives, then emits the latest one after the specified interval.</li><li>throttle waits for the specified interval, then emits either the first or the latest of the values it received during that interval. It doesn’t care about pauses.</li></ul><p><strong>Timing out</strong></p><p>when a timeout operator fires, it either completes the publisher or emits an error you specify. In both cases, the publisher terminates.</p><pre>let subject = PassthroughSubject&lt;Void, Never&gt;()<br>let timedOutSubject = subject.timeout(.seconds(5), scheduler:<br>DispatchQueue.main)</pre><p>or</p><pre>enum TimeoutError: Error {<br>case timedOut<br>}</pre><p>can use it.</p><pre>let subject = PassthroughSubject&lt;Void, TimeoutError&gt;()<br>let timedOutSubject = subject.timeout(.seconds(5), scheduler:<br>DispatchQueue.main, customError:{ .timedOut })</pre><p><strong>Measuring time</strong></p><p>The measureInterval(using:) operator is your tool when you need to find out the time that elapsed between two consecutive values emitted by a publisher.</p><pre><strong>let</strong> subject = PassthroughSubject&lt;Int, Never&gt;()<br><strong>let</strong> measureSubject = subject.measureInterval(using:DispatchQueue.main)</pre><p>Those who follow or read comment down if you have questions. I am planning to write on testing from <a href="https://www.amazon.com/iOS-Unit-Testing-Example-Techniques/dp/1680506811"><strong>iOS Unit Testing by Example</strong></a><strong> and also review </strong><a href="https://www.amazon.com/Head-First-Design-Patterns-Brain-Friendly/dp/0596007124"><strong>Head First Design Patterns</strong></a>. Those are very core books. Everyone should use those as reference books. I also love to write more <strong>algorithm</strong> topics soon. So stay positive and we will learn many things together. <strong>If you want to connect, knock me on </strong><a href="https://www.linkedin.com/in/md-rejaul-hasan-0a5a11131/"><strong>LinkedIn</strong></a>. Happy coding and stay safe.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=493acc67e528" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s play with swift-Part 7]]></title>
            <link>https://rejaul-hasan.medium.com/lets-play-with-swift-part-7-2bc125b322ce?source=rss-9ee5c35f2f32------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bc125b322ce</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Rejaul Hasan]]></dc:creator>
            <pubDate>Mon, 20 Jun 2022 07:19:42 GMT</pubDate>
            <atom:updated>2022-06-20T07:19:42.157Z</atom:updated>
            <content:encoded><![CDATA[<h4>Value Types and value <strong>Semantics, Protocol</strong></h4><blockquote><strong>VALUE SEMANTICS</strong></blockquote><p>This guarantee is that the <em>only </em>way to affect a variable’s value is through that variable itself. If a type promises that, then the type supports value semantics.</p><p><strong>Implementing value semantics</strong></p><p><strong>Case 1: Primitive value types</strong></p><p>Primitive value types like Int support value semantics automatically. This is because assign-by-copy ensures each variable holds its own instance — so no other variable can affect the instance</p><p><strong>Case 2: Composite value types</strong></p><p>Composite value types, for example struct or enum, follow a simple rule: A struct supports value semantics if all its stored properties support value semantics.</p><p><strong>Case 3: Reference types</strong></p><p>To define a reference type with value semantics, you must define it to be <em>immutable</em>. In other words, build it so it’s impossible to change the instance’s value after initialization. To achieve this, you must ensure that all its stored properties are constant and only use types with value semantics.</p><p>example</p><pre>var a = UIImage(named:&quot;smile.jpg&quot;)<br>var b = a<br>computeValue(b) // =&gt; something<br>doSomething(a)<br>computeValue(b) // =&gt; same thing!</pre><p>UIImage, along with many of the Cocoa types, are defined as immutable for this reason, because an immutable reference type has value semantics.</p><p><strong>Case 4: value types containing mutable reference types</strong></p><ol><li>When a mixed-type instance is copied, all of its properties are directly assigned.</li><li>But since any reference-type property is assigned by reference to the copy, the instances of the copy property and the original property will refer to the <em>same </em>shared instance.</li></ol><p>those are the reason that it can not satisfy value semantics. So how can we preserve this rules with case-4 also?</p><p><strong>Copy-on-write to the rescue</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfeca635e5208df8e7db81476429f0c2/href">https://medium.com/media/cfeca635e5208df8e7db81476429f0c2/href</a></iframe><p><strong>Sidebar: property wrappers</strong></p><pre>struct PaintingPlan {<br>var accent = Color.white<br>@CopyOnWriteColor var bucketColor = .blue<br>}</pre><p>The line @CopyOnWriteColor var bucketColor = .blue is automatically expanded by the compiler into the following:</p><pre>private var _bucketColor = CopyOnWriteColor(wrappedValue: .blue)<br>var bucketColor: Color {<br>  get { _bucketColor.wrappedValue }<br> set { _bucketColor.wrappedValue = newValue }<br>}</pre><p>Here is its definition:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3068605e843a92621f9fec5aa3401282/href">https://medium.com/media/3068605e843a92621f9fec5aa3401282/href</a></iframe><p>When in PaintingPlan you assign an initial value of .blue to bucketColor, that actually initializes the property wrapper CopyOnWriteColor, which defines the true backing storage in bucket. And when you access bucketColor in PaintingPlan, you call getters and setters which access the property wrapper’s computed property wrappedValue. And accessing that, in turn, calls the computed properties which you defined in CopyOnWriteColor, and which implement the same copy-on-write logic as our original implementation</p><blockquote><strong>PROTOCOL</strong></blockquote><p><strong>Protocol Extension dispatch</strong></p><pre><strong>protocol</strong> test{<br><strong>var</strong> first: Int {<strong>get</strong>}<br><strong>var</strong> second: Int {<strong>get</strong>}<br>}</pre><pre><strong>extension</strong> test{<br><strong>var</strong> third: Int{3}<br>}</pre><pre><strong>struct</strong> vc: test{<br><strong>var</strong> first: Int<br><strong>var</strong> second: Int<br><strong>var</strong> third: Int{first+second}<br>}</pre><p>Now use it</p><pre><strong>let</strong> ob1 = vc(first: 10, second: 20)<br><strong>let</strong> ob2: test = ob1<br>print(ob1.third, &quot;and&quot;, ob2.third) <br><strong>//output = 30 and 3</strong></pre><p><strong>Type constraints</strong></p><p>Swift lets you write extensions used only when the type adopting a protocol is also another type that you specify. By using a <strong>type constraint </strong>on a protocol extension, you’re able to use methods and properties from another type inside the implementation of your extension.</p><pre><strong>protocol</strong> TeamRecord{<br><strong>var</strong> wins: Int {<strong>get</strong>}<br>}</pre><pre><strong>protocol</strong> PostSeasonEligible {<br><strong>var</strong> minimumWinsForPlayoffs: Int { <strong>get</strong> }<br>}</pre><pre><strong>extension</strong> TeamRecord <strong>where</strong> <strong>Self</strong>: PostSeasonEligible {<br><strong>var</strong> isPlayoffEligible: Bool {<br>wins &gt; minimumWinsForPlayoffs<br>}<br>}</pre><p>You have a new protocol, PostSeasonEligible, that defines a minimumWinsForPlayoffs property. The magic happens in the extension ofTeamRecord, which has a type constraint on Self: PostSeasonEligible that will apply the extension to all adopters of TeamRecord that <em>also </em>adopt PostSeasonEligible.</p><p>Applying the type constraint to the TeamRecord extension means that within the extension, self is known to be both a TeamRecord and PostSeasonEligible. That means you can use properties and methods defined on both of those types.</p><pre>protocol Tieable {<br>   var ties: Int { get }<br>}</pre><pre>extension TeamRecord where Self: Tieable {<br>  var winningPercentage: Double {<br>     Double(wins) / Double(wins + losses + ties)<br>  }<br>}</pre><p>Now any type that is both a TeamRecord and Tieable won’t need to explicitly implement a winningPercentage that factors in ties:</p><pre>struct RugbyRecord: TeamRecord, Tieable {<br>  var wins: Int<br>  var losses: Int<br>  var ties: Int<br>}</pre><pre>let rugbyRecord = RugyRecord(wins: 8, losses: 7, ties: 1)<br>rugbyRecord.winningPercentage // 0.5</pre><p><strong>Existential protocols</strong></p><pre><strong>protocol</strong> Pet {<br><strong>var</strong> name: String { <strong>get</strong> }<br>}</pre><pre><strong>struct</strong> Cat: Pet {<br><strong>var</strong> name: String<br>}</pre><pre>var somePet: Pet = Cat(name: &quot;Whiskers&quot;)</pre><p>Here, you defined the variable somePet with a type of Pet instead of the concrete type Cat. Here Pet is an <strong>existential type </strong>— it’s an abstract concept, a protocol, that refers to a concrete type, a struct, that <em>exists</em>.</p><p><strong>Non-existential protocols or associate type</strong></p><pre>protocol WeightCalculatable {<br>  associatedtype WeightType<br>var weight: WeightType { get }<br>}</pre><p>We can use it through.</p><pre>class HeavyThing: WeightCalculatable {<br>  // This heavy thing only needs integer accuracy<br>  typealias WeightType = Int<br>  var weight: Int {100} <br>}</pre><p><strong>Constraining the protocol to a specific type</strong></p><pre>protocol WeightCalculatable {<br>  associatedtype WeightType: Numeric<br>  var weight: WeightType { get }<br>}</pre><p>This will constraining WeightType only into numaric. Let’s write generic functions that use weights in computations.</p><pre>extension WeightCalculatable {<br>  static func +(left: Self, right: Self) -&gt; WeightType {<br>left.weight + right.weight<br>  }<br>}</pre><pre>var heavy1 = HeavyThing()<br>var heavy2 = HeavyThing()<br>heavy1 + heavy2 // 200<br>var light1 = LightThing()<br>heavy1 + light1 // the compiler detects your coding error</pre><p><strong>Expressing relationships between types</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61b464b82a04b7c888444825ad683549/href">https://medium.com/media/61b464b82a04b7c888444825ad683549/href</a></iframe><p>So, here car factory produce both car and chocolate at the same time. Which is odd and should not produce. So let’s see how we can handle it with generic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcb5438b965fcc7b2199a1187f0389fa/href">https://medium.com/media/fcb5438b965fcc7b2199a1187f0389fa/href</a></iframe><p><strong>Recursive protocols</strong></p><p>You can use a protocol type within that protocol itself, which is called a <strong>recursive protocol</strong>.</p><pre>protocol GraphNode {<br>var connectedNodes: [GraphNode] { get set }<br>}</pre><p><strong>Heterogeneous collections</strong></p><p>Swift collections are <strong>homogeneous</strong>; that is, their elements must be of a single type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdfa70de2f37b42c77f8bec36f024305/href">https://medium.com/media/bdfa70de2f37b42c77f8bec36f024305/href</a></iframe><p>In those three examples, the first only refers to the protocol. The others refer to the concrete class implementing the protocol.</p><p>Unfortunately, the first example doesn’t work because WeightCalculatable is an incomplete type. It has a hole inside it because it requires you to specify the associated type.</p><p>Now try to mix heavy things and light heavy things in the same array</p><pre>var heavyList = [HeavyThing(), VeryHeavyThing()]</pre><p>it will make an error and suggest it as.</p><pre><strong>var</strong> heavyList = [HeavyThing(), VeryHeavyThing()] <strong>as</strong> [<strong>Any</strong>]</pre><p>then it cast any objects.</p><p><strong>Type erasure</strong></p><p>When you want to create a list of different items, you should define the list with a type that each element will conform to.</p><pre>class AnyHeavyThing&lt;T: Numeric&gt;: WeightCalculatable {<br>  var weight: T {<br>      123<br>  } <br>}</pre><pre>class HeavyThing2: AnyHeavyThing&lt;Int&gt; {<br>  override var weight: Int {<br>     100<br>  } <br>}</pre><pre>class VeryHeavyThing2: AnyHeavyThing&lt;Int&gt; {<br>  override var weight: Int {<br>   9001<br>  } <br>}</pre><p>let’s use</p><pre>var heavyList2 = [HeavyThing2(), VeryHeavyThing2()]<br>heavyList2.forEach { print($0.weight) }</pre><p><strong>Opaque return types</strong></p><p>The goal of type erasure is to hide unimportant details about concrete types but still communicate the type’s functionality using a protocol.</p><p>You can illustrate this using the production factory example you saw earlier.</p><p>Create a class type that builds a production factory. and decide in this class what products the factory will create. It handles creating the production lines, the inventory, the employees, the budget… all the hassle in that factory.</p><p>Your colleague working on that project shouldn’t have to know all these implementation details. Only that there’s a factory and it can produce products.</p><p>Before going into the implementation, recall the previous example.</p><pre>var carFactory = GenericFactory&lt;Car&gt;()<br>carFactory.productionLines = [GenericProductionLine&lt;Car&gt;(),<br>GenericProductionLine&lt;Car&gt;()]<br>carFactory.produce()</pre><p>This is how you built the factory that didn’t allow you to add the wrong production. It worked perfectly, <em>but </em>whoever is holding the instance of the factory <em>knows </em>exactly what kind of factory it is. This might be more information than you want to expose.</p><pre>func makeFactory() -&gt; Factory { // compile error<br>GenericFactory&lt;Car&gt;()<br>}<br>let myFactory = makeFactory()</pre><p>Oh… Swift will not allow the use of Factory like this because of its associated type. This is <em>exactly </em>the problem that opaque return types solve. By changing the return type to some Factory, the errors will disappear.</p><pre>func makeFactory(isChocolate: Bool) -&gt; some Factory {<br>  if isChocolate {<br>     return GenericFactory&lt;Chocolate&gt;()<br>  }else {<br>     return GenericFactory&lt;Car&gt;()<br>  }<br>}</pre><p>The compiler, despite knowing the exact concrete type you returned, hides this information behind the Factory protocol. In other words, it knows it’s a GenericFactory&lt;Car&gt;, but all your users see is that it is a Factory.</p><p>Those who follow or read comment down if you have questions. I am planning to write on testing from <a href="https://www.amazon.com/iOS-Unit-Testing-Example-Techniques/dp/1680506811"><strong>iOS Unit Testing by Example</strong></a>. They write for UIKit. I will try to write it in SwiftUI. I also love to write more algorithm topic soon. So stay positive and we will learn many thing together. <strong>If you want to connect, knock me at </strong><a href="https://www.linkedin.com/in/md-rejaul-hasan-0a5a11131/"><strong>LinkedIn</strong></a>. Happy coding and stay safe.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bc125b322ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modularisation ios app]]></title>
            <link>https://rejaul-hasan.medium.com/modularisation-ios-app-a8e38b2816a9?source=rss-9ee5c35f2f32------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8e38b2816a9</guid>
            <category><![CDATA[modularization]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Rejaul Hasan]]></dc:creator>
            <pubDate>Sun, 10 Apr 2022 19:22:19 GMT</pubDate>
            <atom:updated>2022-04-10T19:23:12.895Z</atom:updated>
            <content:encoded><![CDATA[<h4>Library, framework and package</h4><h3>Module</h3><p>iOS and Mac projects are built upon different parts that we call modules. When you start a new, fresh project, your app is built upon one module — the app itself.<br>Well, libraries, frameworks, and Swift Packages are all types of modules, and these are all tools that help us separate our code and make it more reusable.</p><h3>Library</h3><p>One type of module that we have is a library. A library contains a set of classes that have a shared goal. Library do not contain and resource file or assets. It just contain plain code files.</p><p>2 types of library</p><ol><li>Dynamic library</li><li>Static library</li></ol><p><strong>Dynamic library:</strong> dynamic libraries are linked to your app during runtime using dynamic linker. They are not part of your build but have a negative influence on your startup time. Because dynamic libraries link to your app during runtime, you can replace them without shipping a new build. This is why dynamic libraries are not supported in iOS, besides Apple’s own system libraries.<br>Dynamic libraries also have their file extension — it is “.dylib,” and you probably met these types of files when linking system libraries</p><p><strong>Static library:</strong> Static libraries are linked to your app during compilation time. They become part of your app and increase your build size. If you see a file with an “.a” extension, that will be a static library.</p><h3>Framework:</h3><p>Framework is really just a folder that encapsulates resources, code, and other libraries, both dynamic and static. So library just have plain code files and framework can have assets, code and other libraries.</p><p>Libraries produce something called an object file, a binary representation of its code. When frameworks are mostly just folders with code and data, some of them are libraries themselves.</p><h3>Swift Package:</h3><p>Swift Package is somehow similar to a library, although it is not compiled. This kind of library is also a set of classes aimed to solve a particular logic problem, but Swift Package makes packaging and testing processes much more comfortable and straightforward</p><p>Let’s see a simple package configuration file mostly name as Package.swift.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d41f38e4c8273ce95de87514f311b61e/href">https://medium.com/media/d41f38e4c8273ce95de87514f311b61e/href</a></iframe><h3>Let’s define products, library and target</h3><p>package that contains libraries. Like below.</p><pre>products: [<br>.library(<br>name: &quot;MyFirstPackage&quot;,<br>targets: [&quot;MyFirstPackage&quot;]),</pre><pre>.library(<br>name: &quot;MySecondPackage&quot;,<br>targets: [&quot;MySecondPackage&quot;]),<br>],</pre><p>The list of library is called product. And this single library can have many targets as you can see it’s take array. And a target is a single module of code which most of the time responsible to do 1 specific task. Whatever, we import in our code like</p><pre>import Coredata</pre><p>is a target.</p><p>Targets are the “lower level” of your package architecture, and the libraries are the “top level.”</p><p><strong>Library is what you link to your project, and its targets are what you import to your files.</strong></p><p><strong>Can we add resource file in our package?:</strong></p><p>The answer is yes we can. We can add the following types of resources to our package without making any modifications to our manifest file.</p><ul><li>Storyboards and Xib files</li><li>Asset catalogs</li><li>Core Data files</li><li>Localization files (.lproj)</li></ul><p>Once we have resources in our package, a bundle is created during the build and will contain the package resources only (without the code, which still belongs to the main bundle).</p><p>We said that when we add a resource to a package target, we get a dedicated bundle. Instead of</p><pre>Bundle.main.path(forResource: “data”, ofType: “plist”)</pre><p>we need to use</p><pre>Bundle.module.path(forResource: “data”, ofType: “plist”)</pre><p>The module variable is automatically generated if you have at least one resource in your target folder and won’t exist for packages without resources.</p><p><strong>Can we add framework in our package?:</strong></p><p>Yes, we can. We can add framework from local path or from url where our framework hosted.</p><p><strong>N.B:</strong> We can combine 2–3 framework into one framework also. After archiving framework it will be a binary code and we can add this into our package.</p><p><strong>So conclusion is:</strong></p><p><strong>library:</strong> just hold code file. nothing else. <strong>Static library:-</strong> make binary inside the main app compile time. Make our app larger. Static library or framework do not need to embed because it’s code stay in the main app binary. If you have resources then you should embed it. So that it will create a bundle to access the assets. If you embed it without resource file exist, you just make your app size larger because you make a binary copy and framework folder of the library which is already in your app main binary. <strong>Dynamic Library:</strong>- It should be embed. Otherwise dynamic linker will not find it because it’s execute in run time and can not find the framework. It’s binary are not with the main app binary.</p><p><strong>framework</strong>: Can hold asset and code files also.</p><p><strong>package:</strong> can have 2–3 library. We can add resources and framework also.</p><p><a href="https://rejaul-hasan.medium.com/coupling-in-swift-9f73fa6024c6"><strong>Coupling in Swift</strong></a><strong> </strong>is an important topic to read, helps you to learn how to decouple module, class dependency<strong>. Dependency Injection</strong> is another important topic to discuss. It help us to design and write good API. I will talk about it soon. Many example are taken from the book <a href="https://www.amazon.com/Mastering-Swift-Package-Manager-Modular/dp/1484270487">Mastering Swift Package Manager</a>. If you want to read more have a consideration of this book. This <a href="https://www.youtube.com/watch?v=IqsKGyklmL0">video</a> is good in short. Want to connect? <a href="https://www.linkedin.com/in/md-rejaul-hasan-0a5a11131/">Knock me.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8e38b2816a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coupling in Swift]]></title>
            <link>https://rejaul-hasan.medium.com/coupling-in-swift-9f73fa6024c6?source=rss-9ee5c35f2f32------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f73fa6024c6</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Rejaul Hasan]]></dc:creator>
            <pubDate>Wed, 06 Apr 2022 06:50:22 GMT</pubDate>
            <atom:updated>2022-04-06T06:50:22.999Z</atom:updated>
            <content:encoded><![CDATA[<p>Code coupling is the level of connection between two software components. The more abstract way to describe code coupling is “Is changing one class code mean I need to change another class?”</p><h3>Types of Coupling:</h3><ol><li>Structural Dependencies</li><li>Fan-Out Similarity</li><li>Logical Coupling</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*WEAA2HhBkv2OqrUM9dmMBQ.png" /></figure><p><strong>Structural Dependencies:</strong></p><p>Structural dependencies are the “classic” dependencies we know. It mostly means a “direct connection between classes or components.” For example, when a class calls another class method, it’s a structural dependency.</p><p>3 types</p><ol><li>inheritance</li><li>aggregates</li><li>usage</li></ol><p><strong>Inheritance</strong>:</p><p>Inheritance is probably one of the most coupled design patterns that exist. It’s practically a pure definition of code coupling — every change in the base class influences its subclasses (unless mentioned otherwise), and this operation is done recursively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IttqOA65l5ORFgvx4c6jtA.png" /></figure><p><strong>Aggregation</strong>:</p><p>Aggregation is a type of composition where one class uses another class and has an instance variable of the latest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J6LKwCi_wOri5rDDGJjLkg.png" /></figure><p><strong>Usages</strong>:</p><p>In the “usage” coupling type, one class usually has a method with a parameter based on another class. This one is considered to be a more “light” coupling</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/505d89b086ba42fe80227793ce5a27e5/href">https://medium.com/media/505d89b086ba42fe80227793ce5a27e5/href</a></iframe><p>In the preceding example, Team doesn’t have a reference to Employee, but one of its methods does, in its parameter.<br>One way to avoid it is to try “shaving” the objects being passed to what we need.<br>For example, if what we need from the “Employee” object is its age, we can just pass a list of Int:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/161454e20efdb62c32a4128e2b82c30a/href">https://medium.com/media/161454e20efdb62c32a4128e2b82c30a/href</a></iframe><p><strong>Fan-Out Similarity:</strong></p><p>Fan-Out — The number of modules called by a given module<br>Fan-In — The number of modules that call a given module</p><p>the list of connected modules in Fan-Out represents a particular functionality. If we find two (or more) modules with the same list of modules, it might indicate a similar functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9v4EveZQX4MxaBmMlvzXyQ.png" /></figure><p>The higher the number of modules in this shared set, the higher the chances that both modules have similar functionality.</p><p>In that case, this is a chance for us to create another abstract layer that encapsulates this pattern and, by definition, reduces the coupling level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xYLjnlJobslQ-bkLcMlDrQ.png" /></figure><p>In the Figure, we can see that AlbumsService and PlaylistsService now have low Fan-Out Similarity while referencing only one component instead of three.</p><p><strong>Logical Coupling:</strong></p><p>Logical coupling, also known as evolutionary coupling, is when two modules code changes and modify together. If code changes in one module frequently mean code changes in another module, it may point out some coupling level.</p><p>If we detect such coupling , we can try to understand the reason for that. For example, one reason could be <strong>duplicate code</strong>. Creating another component to encapsulate this code can be the right solution for that.</p><p><strong>Dependency Injection</strong> is another important topic to discuss. It help us to design and write good API. I will talk about it soon. Many example and screenshot are taken from the book <a href="https://www.amazon.com/Mastering-Swift-Package-Manager-Modular/dp/1484270487">Mastering Swift Package Manager</a>. If you want to read more have a consideration of this book. Want to connect? <a href="https://www.linkedin.com/in/md-rejaul-hasan-0a5a11131/">Knock me.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f73fa6024c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Document your swift code]]></title>
            <link>https://rejaul-hasan.medium.com/document-your-swift-code-6eb1223c53d6?source=rss-9ee5c35f2f32------2</link>
            <guid isPermaLink="false">https://medium.com/p/6eb1223c53d6</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Rejaul Hasan]]></dc:creator>
            <pubDate>Wed, 30 Mar 2022 11:58:26 GMT</pubDate>
            <atom:updated>2022-05-19T09:29:02.064Z</atom:updated>
            <content:encoded><![CDATA[<h4>Use the Xcode build in features</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ieXaavHBhInXJiKyK4RTEA.jpeg" /><figcaption><a href="https://unsplash.com/">https://unsplash.com</a></figcaption></figure><p>It’s a short note of how we can document your swift code properly. Let’s see some examples instead of writing. This way, I think we can learn more.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be7299539c8f60b46890702f187644d8/href">https://medium.com/media/be7299539c8f60b46890702f187644d8/href</a></iframe><p>And that’s how it looks in our quick help inspector.</p><figure><img alt="doc" src="https://cdn-images-1.medium.com/max/802/1*y_iAmlIA-iXDjTa7b4BJAQ.png" /><figcaption>doc1</figcaption></figure><p>We can write custom code in a comment using 3 ~ or ` by opening and closing. let’s see that example also.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc5bb755090cced75a24d20678591dbc/href">https://medium.com/media/dc5bb755090cced75a24d20678591dbc/href</a></iframe><p>and the output is the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*ye1mEf3jfjpdp8TYuy2SvA.png" /><figcaption>doc2</figcaption></figure><p>Summary and Declaration are taken using paragraph or line gap when we write. So, this is how we can document our function, class, struct, and design a good well-written library.</p><p>Here is the article on <a href="https://rejaul-hasan.medium.com/modularisation-ios-app-a8e38b2816a9">modularisation</a>. Want to connect? <a href="https://www.linkedin.com/in/md-rejaul-hasan-0a5a11131/">knock me.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6eb1223c53d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Concurrency — Part2]]></title>
            <link>https://rejaul-hasan.medium.com/swift-concurrency-part2-ca2bc0b2710b?source=rss-9ee5c35f2f32------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca2bc0b2710b</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[operations]]></category>
            <dc:creator><![CDATA[Rejaul Hasan]]></dc:creator>
            <pubDate>Mon, 04 Oct 2021 07:13:25 GMT</pubDate>
            <atom:updated>2022-03-27T10:40:02.007Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift Concurrency</h3><h4><strong>Learning about Operations</strong></h4><figure><img alt="Parallel data flow" src="https://cdn-images-1.medium.com/max/1024/1*llXmRqzdmko3WpALGS-Jhw.jpeg" /></figure><p><strong>BlockOperation</strong></p><p>A BlockOperation manages the <em>concurrent </em>execution of one or more closures on the default global queue. This provides an object-oriented wrapper for apps that are already using an OperationQueue (discussed in the next chapter) and don’t want to create a separate DispatchQueue as well</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c5738193a6b9a7cf293dbc11cce77a5/href">https://medium.com/media/3c5738193a6b9a7cf293dbc11cce77a5/href</a></iframe><p>BlockOperation manages a <strong>group </strong>of closures. It acts similar to a dispatch group in that it marks itself as being finished when all of the closures have finished.</p><p><strong>Note</strong>: Tasks in a BlockOperation run concurrently. If you need them to run serially, submit them to a private DispatchQueue or set up dependencies.</p><p>When you want to add additional closures to the BlockOperation, you’ll call the addExecutionBlock method and simply pass in a new closure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e91d1a1fb11c728763a49d1b6678a1f0/href">https://medium.com/media/e91d1a1fb11c728763a49d1b6678a1f0/href</a></iframe><p>Remember that a BlockOperation runs <em>concurrently</em>, not <em>serially</em>, and thus the order of execution is not deterministic.</p><p>If you provide a completionBlock closure, then it will be executed once all of the closures added to the block operation have finished.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef251d1300db39a79310d920c7ac742b/href">https://medium.com/media/ef251d1300db39a79310d920c7ac742b/href</a></iframe><p><strong>Subclassing operation</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93ce29407504948b6d2f395468ea476b/href">https://medium.com/media/93ce29407504948b6d2f395468ea476b/href</a></iframe><p>The above one is the <strong>Operation</strong> class define by apple team. It has some extension but it’s the important part. Let’s try to understand.</p><p><strong>open var isCancelled: Bool { get }:</strong> A Boolean value indicating whether the operation has been cancelled</p><p><strong>open var isExecuting: Bool { get }:</strong> A Boolean value indicating whether the operation is currently executing.</p><p><strong>open var isFinished: Bool { get }:</strong> A Boolean value indicating whether the operation has finished executing its task.</p><p><strong>open func cancel():</strong> Advises the operation object that it should stop executing its task.</p><p><strong>addDependency and removeDependency</strong>: As the name suggest.</p><p>So, it able to give you some information of different state and give some more functionality.</p><p>Most Important 2 function</p><p><strong>start():</strong> Begins the execution of the operation.</p><p><strong>main():</strong> <strong>The default implementation of this method does nothing. You should override this method to perform the desired task. In your implementation, do not invoke </strong><strong>super. This method will automatically execute within an autorelease pool provided by </strong><strong>NSOperation, so you do not need to create your own autorelease pool block in your implementation.</strong></p><p><strong>If you are implementing a concurrent operation, you are not required to override this method but may do so if you plan to call it from your custom </strong><strong>start() method.</strong></p><p>So, <strong>start()</strong> calls <strong>main()</strong> method and <strong>main()</strong> is the method where we should define our task which we want to run concurrently. Like we can implement network call in it. Let’s see the example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23a0667c774db85d7a0a536a8f3acfc0/href">https://medium.com/media/23a0667c774db85d7a0a536a8f3acfc0/href</a></iframe><p>Here, we create a <strong>Operation</strong> subclass name <strong>Test</strong>. <strong>Test</strong> do some heavy task inside the main() function than update the variable <strong>data</strong>. Downside we try to get the total time needed to run the task. We download 3 image and assume every image take 2 min to download. As Operation run concurrently so it may take 2.2–2.5 min to download all images but let’s see the output.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a647d92e3225e1f5f93c67fd0deaaf94/href">https://medium.com/media/a647d92e3225e1f5f93c67fd0deaaf94/href</a></iframe><p>So, it looks like run serially and take 6 second to download 2s per image.So, why it happen?</p><p>When you call the start method directly on an operation, you’re performing a <strong>synchronous </strong>call on the <strong>current thread </strong>(i.e., the main thread). So while the code has been refactored into an Operation subclass, you’re not yet taking advantage of the concurrency opportunities provided therein.</p><p><strong>Note</strong>: Besides the fact that calling <strong>start</strong> runs the operation on the current thread, it can also lead to an <strong>exception if the operation is not yet ready to be started</strong>. Generally, you shouldn’t call start manually, unless you really know what you’re doing!</p><p><strong>OperationQueue</strong></p><p>the OperationQueue class is what you use to manage the scheduling of an Operation and the maximum number of operations that can run simultaneously.</p><ul><li>Pass an Operation.</li><li>Pass a closure.</li><li>Pass an array of Operations.</li></ul><p>operation by itself is a synchronous task. While you could dispatch it asynchronously to a GCD queue to move it off the main thread, you’ll want, instead, to add it to an OperationQueue to gain the full concurrency benefits of operations</p><p><strong>OperationQueue management</strong></p><p>Once you’ve added an Operation to the queue, it will run until it has completed or been canceled.Once you’ve added an Operation to an OperationQueue, you can’t add that same Operation to any other OperationQueue. Operation instances are <strong>once and done </strong>tasks, which is why you make them into subclasses so that you can execute them multiple times, if necessary.</p><p><strong>Waiting for completion</strong></p><p><strong>waitUntilAllOperationsAreFinished</strong>:- Calling it blocks the current thread, meaning that you must never call this method on the main UI thread.</p><p><strong>addOperations(_:waitUntilFinished:):-</strong> If you don’t need to wait for all operations to complete, but just a set of operations, then you can, instead, use the addOperations(_:waitUntilFinished:) method on OperationQueue.</p><p><strong>Quality of service</strong></p><p>An OperationQueue behaves like a DispatchGroup in that you can add operations with different quality of service values and they’ll run according to the corresponding priority.</p><p><strong>Pausing the queue</strong></p><p>You can pause the dispatch queue by setting the isSuspended property to true. In- flight operations will continue to run but newly added operations will not be scheduled until you change isSuspended back to false.</p><p><strong>Maximum number of operations</strong></p><p>By default, the dispatch queue will run as many jobs as your device is capable of handling at once. If you wish to limit that number, simply set <strong>the maxConcurrentOperationCount</strong> property on the dispatch queue. If you set the <strong>maxConcurrentOperationCount</strong> to 1, then you’ve effectively created a serial queue.</p><p><strong>Underlying DispatchQueue</strong></p><p>Before you add any operations to an OperationQueue, you can specify an existing DispatchQueue as the underlyingQueue. If you do so, keep in mind that the <strong>quality of service of the dispatch queue will override any value you set for the operation queue’s quality of service</strong>.</p><p>So, let’s use Operationqueue for the same task.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b06bddd4e0b13effcab6e40f3c1076a/href">https://medium.com/media/9b06bddd4e0b13effcab6e40f3c1076a/href</a></iframe><p>So, here we use <strong>operation queue</strong> to run our <strong>operation</strong> concurrently. When one <strong>operation</strong> finish, it will call <strong>completionBlock</strong> and inside completion block we print <strong>op.data</strong>. When all the operation finish(<strong>waitUntilAllOperationsAreFinished</strong>), we print the total time.</p><p>Notice:- here we block the main thread. It will not happen in real world.</p><p>Let’s see the output.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/841f3d9682de47e95756a7d585fd338f/href">https://medium.com/media/841f3d9682de47e95756a7d585fd338f/href</a></iframe><p>See, the image are not maintain any serial and also look at the time, it takes 2.038 seconds. So all 3 task or operation run parallel.</p><p><strong>Asynchronous Operations &amp; Cancel operations</strong></p><p>In all previous examples the operations itself are serial. The operation run in parallel in operation queue but single operation are serial. So the operation state going very straight.</p><p><strong>isReady -&gt; isExecuting -&gt; isFinished</strong></p><p>How would that work with an <em>asynchronous </em>operation, though? When the main method of the operation executes, it will kick off your asynchronous task, and then <strong>main</strong> exits. The state of the operation can’t switch to <strong>isFinished</strong> at that point because the asynchronous method likely has yet to complete. As, <strong>main</strong> exit, so operation by default assume the work finish. So, we should override those and give proper notification when the task actually finish. Let’s see an example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0f3aa53ed5568e8e0b3fbae31f09530/href">https://medium.com/media/b0f3aa53ed5568e8e0b3fbae31f09530/href</a></iframe><p>Here, we override all state <strong>isReady</strong>, <strong>isExecuting</strong>, <strong>isFinished</strong> and set them <strong>true</strong> or <strong>false</strong> according to our custom made <strong>State</strong>. Let’s try to download an image using this class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c84737bbb11ced3befa2a5bf22a055d/href">https://medium.com/media/8c84737bbb11ced3befa2a5bf22a055d/href</a></iframe><p>See here, we also override <strong>cancel</strong> function. So that if you want to cancel our operation task we are going to cancel our <strong>URLSessionTask</strong> also. You are checking <strong>isCancel</strong> state several places so that when it get a <strong>cancel</strong> it will return. Let’s use this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85116172427ef5e5c36127fe54f32e30/href">https://medium.com/media/85116172427ef5e5c36127fe54f32e30/href</a></iframe><p>and the output is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6A5r8-md8Sx64CKyhYiVDg.png" /></figure><p>So, the image is properly downloaded. If you want to cancel the operation task you can call.</p><pre>op.cancel()</pre><p>it will cancel you operation.</p><p><strong>Operation Dependencies</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7998085a8ba14e80c9e8ed207ed4ac34/href">https://medium.com/media/7998085a8ba14e80c9e8ed207ed4ac34/href</a></iframe><p>Here, operation 1 start his work with 5 second delay and it give an output which is an integer. <strong>OpOne</strong> confirm the protocol ShareData and pass the output to the Operation2, because operation2 look after it’s dependency that anyone give the integer or not by using this small code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da2df6c1255fc451c8dad4a5b53bd1ef/href">https://medium.com/media/da2df6c1255fc451c8dad4a5b53bd1ef/href</a></iframe><p><strong>Op2</strong> have a dependency on <strong>Op1</strong>. <strong>op2.addDependency(op1)</strong>. Now, let’s see the output.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50c883022ea92ab091b4d20e533b3df9/href">https://medium.com/media/50c883022ea92ab091b4d20e533b3df9/href</a></iframe><p>See, op2 use the data coming from op1 and op2 start it’s work after 5 second as it is waiting for the operation 1 finish.</p><p><strong>DeadLock</strong></p><p>When you add your dependency looks after you dependency graph. Is it falling any loop. See some example image taken from the book</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sp8QBG-I_QgWCMgtiEl4mQ.png" /></figure><p>Also not a deadlock</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GKZ2Z_vq5_0i-mDI5oj4jQ.png" /></figure><p>but the last one has a probability to fall into deadlock</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z-oXuGJOLQS-XYUkpXm2Lw.png" /></figure><p>The article is written from my working experience with different project where I face similar types of problems, the book name <a href="https://www.raywenderlich.com/books/concurrency-by-tutorials/v2.0">concurrency by tutorials</a> and apple documentation. The part1 is <a href="https://medium.com/@rejaul-hasan/swift-concurrency-part1-fe60a6eddd6b">here</a>. I use their(Book) reference and examples in the article, as they explain and summarise nicely. I recommend to read it, as it’s a very short book, help you to recall your previous knowledge and at the same time give you some extra inside knowledge. The cover photo is taken from <a href="https://unsplash.com/">unsplash</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca2bc0b2710b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>