<?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 Valsamis Elmaliotis on Medium]]></title>
        <description><![CDATA[Stories by Valsamis Elmaliotis on Medium]]></description>
        <link>https://medium.com/@valsamiselmaliotis?source=rss-3caea706aa38------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*GI3jXHEhqd7CFNAgpi_nvQ.jpeg</url>
            <title>Stories by Valsamis Elmaliotis on Medium</title>
            <link>https://medium.com/@valsamiselmaliotis?source=rss-3caea706aa38------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 00:42:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@valsamiselmaliotis/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[One Time Password (OTP) in Swift]]></title>
            <link>https://medium.com/@valsamiselmaliotis/one-time-password-otp-in-swift-920601f66769?source=rss-3caea706aa38------2</link>
            <guid isPermaLink="false">https://medium.com/p/920601f66769</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[otp]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[sms]]></category>
            <dc:creator><![CDATA[Valsamis Elmaliotis]]></dc:creator>
            <pubDate>Wed, 30 Oct 2019 10:43:54 GMT</pubDate>
            <atom:updated>2019-10-30T10:43:54.954Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this story, we will learn how to use UITextField “One Time Code” mechanism.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fh1cT-nbCLR4Ube_" /><figcaption>Photo by <a href="https://unsplash.com/@neonbrand?utm_source=medium&amp;utm_medium=referral">NeONBRAND</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Many times we have seen applications to require an SMS security code fill, before continue with a specific feature. In this story we will see how we can use UITextField’s “One Time Code” <strong>Content Type,</strong> in order to autofill an SMS security code.</p><p>Start a new Project and add a UITextField in the Storyboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K_mGbkZHmq9ObgotXC-IOA.png" /></figure><p>Now select it and from the Property Inspector change it’s <strong>Content Type</strong> property to “One Time Code”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*-gqirFINajLf602qWLxZuQ.png" /></figure><p>Or via code in viewDidLoad method</p><pre><strong>class</strong> ViewController: UIViewController {</pre><pre><strong>    @IBOutlet</strong> <strong>weak</strong> <strong>var</strong> optTextField: UITextField!</pre><pre><strong>    override</strong> <strong>func</strong> viewDidLoad() {<br>        <strong>super</strong>.viewDidLoad()<br>        optTextField.textContentType = .oneTimeCode<br>    }<br>}</pre><p>Now Run the app in a real device and sent an SMS with text “Code 4321” to your phone.</p><blockquote>The SMS text must contain the word “Code” or “passcode” and the text must be copyable.</blockquote><p>Once the SMS is received</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*o8xZGIqlCtfYjrK-24bLog.png" /></figure><p>You can tap the on the top of Keyboard now to autofill the code to the UITextField.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*dNY4hhCZM5dXJeYTg9TgNw.png" /></figure><blockquote>The OTP only works with the Default Keyboard</blockquote><p>See you in the next story!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=920601f66769" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mock a Network Call in Swift]]></title>
            <link>https://medium.com/@valsamiselmaliotis/mock-a-network-call-in-swift-6553ecdd3b81?source=rss-3caea706aa38------2</link>
            <guid isPermaLink="false">https://medium.com/p/6553ecdd3b81</guid>
            <category><![CDATA[unitt-testing]]></category>
            <category><![CDATA[mock]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Valsamis Elmaliotis]]></dc:creator>
            <pubDate>Thu, 17 Oct 2019 11:21:03 GMT</pubDate>
            <atom:updated>2019-10-17T11:21:03.681Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this story we will see how we can Mock a Network Call so we can write Tests.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d973bhk9Sf1Eu9E_" /><figcaption>Photo by <a href="https://unsplash.com/@ninaz?utm_source=medium&amp;utm_medium=referral">Nina Ž.</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Writing Tests in a project is something your team must do.<br>Tests will help you catch bugs early and save development and QA time.</p><p>When we make a network call in our Swift project, we do not want to test the real Server communication. Tests must not depend on external faulty resources. If the network go down if the middle of a test, you will get a failure and this failure does not mean there is something wrong with your code.</p><p>In order to avoid this we will have to <strong>Mock</strong> the network call, and provide the network result with our own data to test.</p><p>Let’s get our hands dirty!<br>We will use iTunes search API to test our network call.</p><h3>1. Simple Network Call</h3><p>Create a new Xcode project named “URLMockDemo”.</p><p>In ViewController create the viewDidAppear function.</p><pre><strong>override</strong> <strong>func</strong> viewDidAppear(<strong>_</strong> animated: Bool) {<br>    <strong>super</strong>.viewDidAppear(animated)<br>}</pre><p>Inside viewDidAppear we will make our network call request.<br>Before we go on let’s create our <strong>models</strong> and a simple <strong>NetworkClient</strong>.</p><p>An iTunes search <strong>json</strong> will look like this:</p><pre>{<br>    &quot;resultCount&quot; : 1,<br>    &quot;results&quot; : [<br>    {<br>        &quot;artistId&quot; : 1093102,<br>        &quot;artistName&quot; : &quot;The Prodigy&quot;,<br>        &quot;artistViewUrl&quot; : &quot;<a href="https://music.apple.com/">https://music.apple.com/</a>...&quot;,<br>        &quot;artworkUrl100&quot; : &quot;<a href="https://is4-ssl.mzstatic.com/image/...jpg">https://is4-ssl.mzstatic.com/...jpg</a>&quot;,<br>        &quot;artworkUrl30&quot; : &quot;<a href="https://is4-ssl.mzstatic.com/image/...jpg">https://is4-ssl.mzstatic.com/...jpg</a>&quot;,<br>        &quot;artworkUrl60&quot; : &quot;<a href="https://is4-ssl.mzstatic.com/image/thumb/..jpg">https://is4-ssl.mzstatic.com/image...jpg</a>&quot;,<br>        &quot;collectionCensoredName&quot; : &quot;The Fat of the Land&quot;,<br>        &quot;country&quot; : &quot;USA&quot;,<br>        &quot;currency&quot; : &quot;USD&quot;,<br>        &quot;kind&quot; : &quot;song&quot;,<br>        &quot;previewUrl&quot; : &quot;<a href="https://audio-ssl.itunes.apple.com/...m4a">https://audio-ssl.itunes.apple.com/...m4a</a>&quot;,<br>        &quot;primaryGenreName&quot; : &quot;Electronic&quot;,<br>        &quot;releaseDate&quot; : &quot;1996-11-11T12:00:00Z&quot;,<br>        &quot;trackCount&quot; : 10,<br>        &quot;trackId&quot; : 500162140,<br>        &quot;trackName&quot; : &quot;Breathe&quot;<br>    }<br>    ]<br>}</pre><p>We are interested in “<strong>artistName</strong>”, “<strong>trackId</strong>”, “<strong>trackName</strong>”.<br>So let’s create out <strong>Track Model</strong>.</p><p>First create a new Swift file named “Track” and put it in a Group named “Models”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*JOEaiAp58uNZ3H-jgVsDyw.png" /></figure><p>Now create a Struct named Track:</p><pre><strong>struct</strong> Track: Codable {<br>    <strong>var</strong> artistName: String<br>    <strong>var</strong> trackId: Int<br>    <strong>var</strong> trackName: String<br>}</pre><p>Track conform to <strong>Codable</strong> in order to match our properties from the Json output.<br>Because in the Json the tracks information are wrapped in a “results” array key, we will create another Struct named “TrackStore” that also conform to Codable to successfully match the Json output.</p><pre><strong>struct</strong> TrackStore: Codable {<br>    <strong>var</strong> results: [Track] = []<br>}</pre><p>The final Track swift file will look likt this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*Jo_C7yeMCuVyFfAHBfozKA.png" /></figure><p>Our Models are completed. Let’s create the NetworkClient now<br>Create a new Swift file named “NetworkClient”. Put it inside a Group named “Networking”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*aUioXORN5zYP4Fm5neaZEw.png" /></figure><p>Now create a Class named “NetworkClient”</p><pre><strong>import</strong> Foundation</pre><pre><strong>class</strong> NetworkClient {}</pre><p>Inside NetworkClient we will create a method to perform the network call request:</p><pre><strong><em>func</em></strong><em> searchItunes(url: URL, completion: </em><strong><em>@escaping</em></strong><em>  (</em><strong><em>_</em></strong><em> trackStore: TrackStore?, </em><strong><em>_</em></strong><em> errorMessage: String?) -&gt; Void) {</em></pre><pre><em>    </em><strong><em>let</em></strong><em> dataTask = URLSession.shared.dataTask(with: url) { (data,   response, error) </em><strong><em>in</em></strong></pre><pre><em>        //1<br>        </em><strong><em>guard</em></strong><em> </em><strong><em>let</em></strong><em> statusCode = (response </em><strong><em>as</em></strong><em>? HTTPURLResponse)?.statusCode </em><strong><em>else</em></strong><em> {<br>           </em><strong><em>return<br>        </em></strong><em>}</em></pre><pre><em>        //2<br>        </em><strong><em>guard</em></strong><em> </em><strong><em>let</em></strong><em> data = data </em><strong><em>else</em></strong><em> {<br>            completion(</em><strong><em>nil</em></strong><em>, &quot;No Data&quot;)<br>            </em><strong><em>return<br>        </em></strong><em>}</em></pre><pre><em>        //3<br>        </em><strong><em>switch</em></strong><em> statusCode {<br>    <br>        //4<br>        </em><strong><em>case</em></strong><em> 200:<br>            </em><strong><em>let</em></strong><em> trackStore = </em><strong><em>try</em></strong><em>! JSONDecoder().decode(TrackStore.</em><strong><em>self</em></strong><em>, from: data)<br>            completion(trackStore, </em><strong><em>nil</em></strong><em>)</em></pre><pre><em>        //5<br>        </em><strong><em>case</em></strong><em> 404:<br>            completion(</em><strong><em>nil</em></strong><em>, &quot;Bad Url&quot;)<br>        </em><strong><em>default</em></strong><em>:<br>        //6<br>        </em>completion(<strong>nil</strong>, &quot;statusCode: \(statusCode)&quot;)<em><br>        }<br>    }</em></pre><pre><em>    dataTask.resume()<br>}</em></pre><p>We call our method “searchItunes”. As parameter takes a URL and provide a completion block returning a TrackStore (the model that contains all the Track models) and an errorMessage as String.</p><p>We create the URLSessionDataTask form the shared URLSession passing the URL parameter. After the network call is finished and we have a server response, we check if we have a status code, otherwise we return (1).</p><p>Next we check if we have returned data, otherwise we return passing “No Data” as error message to the completion block. (2)</p><p>Next we check the status code (3)</p><p>In case of 200 (4), we create a TrackStore Model form the JSONDecoder, and pass it to our completion block.</p><p>In case of 404 (5), we return passing “Bad Url” as error message to the completion block.</p><p>In any other case (6), we we return passing “statusCode: \(statusCode)” as error message to the completion block.</p><p>Ok it’s time to test our network call.<br>Go to the ViewController swift file in the viewDidAppear method and write this code:</p><pre><strong>override</strong> <strong>func</strong> viewDidAppear(<strong>_</strong> animated: Bool) {<br>    <strong>super</strong>.viewDidAppear(animated)</pre><pre><em>    //1<br>    </em><strong>let</strong> url = URL(string: &quot;https://itunes.apple.com/search?term=prodigy&amp;limit=1&quot;)!</pre><pre><em>    //2<br>    </em><strong>let</strong> networkClient = NetworkClient()</pre><pre><em>    //3<br>    </em>networkClient.searchItunes(url: url) { trackStore, errorMessage  <strong>in<br>        </strong><em>//4<br>        </em>print(trackStore ?? &quot;&quot;)<br>        print(trackStore?.results.first ?? &quot;&quot;)<br>        print(errorMessage ?? &quot;&quot;)<br>    }<br>}</pre><p>First we create the URL of the web url we want to reach. In our case we want to search from the iTunes search API the music tracks of a Music Band called “Prodigy” 😃<br>For a simpler result we have set the results limit to just One.</p><p>Build and Run…<br>In the console you will see:</p><pre><strong>TrackStore(results: [URLMockDemo.Track(artistName: &quot;The Prodigy&quot;, trackId: 500162140, trackName: &quot;Breathe&quot;)])</strong></pre><pre><strong>Track(artistName: &quot;The Prodigy&quot;, trackId: 500162140, trackName: &quot;Breathe&quot;)</strong></pre><p>We successfully fetched the response and created our Models!</p><h3>2. Dependency Injection</h3><p>Our NetworkClient works great and we can search for music tracks!<br>But it is tight coupled with <strong>URLSession</strong> and <strong>URLSessionDataTask</strong>. That means we cannot overcome the real network call in our Tests. To solve this problem we have to make our NetworkClient independent form URLSession and URLSessionDataTask.</p><p>Here is where <strong>Dependency Injection</strong> comes in…<br>We will make URLSession to be injectable in the initialisation of our NetworkClient.</p><p>Let’s create a new Swift file named “NetworkClient+Mock” inside Networking Group. In this file we will create everything we need for our Dependency Injection and Mocking mechanisms. Let’s start with URLSessionDataTask.</p><p>Everything starts with a <strong>protocol</strong>…</p><pre><em>// MARK: - DataTask</em></pre><pre><em>//1<br></em><strong>protocol</strong> URLSessionDataTaskProtocol {</pre><pre><em>    //2<br>    </em><strong>func</strong> resume()<br>}</pre><pre><em>//3<br></em><strong>extension</strong> URLSessionDataTask: URLSessionDataTaskProtocol {}</pre><p>We define a protocol named “URLSessionDataTaskProtocol” (1)<br>This protocol has only one required function named “resume” (2)<br>“resume” must be familiar to you… URLSessionDataTask uses resume to start executing a network request.<br>Next we make an extension to URLSessionDataTask, and make it conform to our URLSessionDataTaskProtocol we created. Since URLSessionDataTask already has a function named “resume” by default we will get no errors!<br>That’s it for now for URLSessionDataTask. Let’s continue with URLSession.</p><pre><em>// MARK: - URLSession</em></pre><pre><em>//1<br></em><strong>protocol</strong> URLSessionProtocol {</pre><pre><em>    //2<br>    </em><strong>func</strong> dataTask(with url: URL, completionHandler: <strong>@escaping</strong> (Data?, URLResponse?, Error?) -&gt; Void) -&gt; URLSessionDataTaskProtocol<br>}</pre><pre><em>//3<br></em><strong>extension</strong> URLSession: URLSessionProtocol {</pre><pre><em>    //4<br>    </em><strong>func</strong> dataTask(with url: URL, completionHandler: <strong>@escaping</strong> (Data?, URLResponse?, Error?) -&gt; Void) -&gt; URLSessionDataTaskProtocol   {</pre><pre><em>        //5<br>        </em><strong>return</strong> (dataTask(with: url, completionHandler: completionHandler) <strong>as</strong> URLSessionDataTask) <strong>as</strong> URLSessionDataTaskProtocol<br>    }<br>}</pre><p>Again we define a protocol named “URLSessionProtocol” (1) with one required method named “<strong>dataTask(with url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -&gt; Void) -&gt; URLSessionDataTaskProtocol</strong>” (2).</p><p>This method is also familiar… BUT instead of returning a URLSessionDataTask it returns our custom protocol URLSessionDataTaskProtocol.</p><p>Next we create an extension to make URLSession conform to our protocol (3).<br>We create the required method (4) and this time we return dataTask method as URLSessionDataTask (Foundation method) and then as URLSessionDataTaskProtocol (protocol required return type) (5).<br>Again we have no errors 😀</p><p>Now it’s time to create our Dependency Injection mechanism for NetworkClient. Go to NetworkClient Swift d make these changes:</p><pre><strong>class</strong> NetworkClient {</pre><pre><em>//1<br></em><strong>private</strong> <strong>var</strong> session: URLSessionProtocol</pre><pre><em>//2<br></em><strong>init</strong>(withSession session: URLSessionProtocol = URLSession.shared) {<br>    <strong>self</strong>.session = session<br>}</pre><pre><strong>func</strong> searchItunes(url: URL, completion: <strong>@escaping</strong>  (<strong>_</strong> trackStore: TrackStore?, <strong>_</strong> errorMessage: String?) -&gt; Void) {</pre><pre><em>//3<br></em><strong>let</strong> dataTask = session.dataTask(with: url) { (data, response, error) <strong>in</strong></pre><pre>...</pre><p>We create a private property named “session” of type URLSessionProtocol (1).<br>Next we create a n initializer for NetworkClient that takes one parameter session of type URLSessionProtocol and with default value URLSession.shared (2). If we do not provide any parameter the NetworkClient will use Foundation’s default shared URLSession.</p><p>Finally where we create the dataTask se use the session property (3).<br>The final code must be like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hXG56_kZMRtCvtSohAyJKQ.png" /></figure><p>Ok let’s build and Run ….<br>As we can we we still get our print values form the Real Network call.<br>The advantage is that URLSession and URLSessionDataTask are no more tight coupled dependencies! 😎</p><h3>3. Mocking</h3><p>Now we can use our protocols to create mocked versions of URLSession and URLSessionDataTask. Let’s start with URLSessionDataTask.</p><p>Go to NetworkClient+Mock Swift file and add this code in the URLSessionDataTask section:</p><pre><em>//1<br></em><strong>class</strong> MockURLSessionDataTask: URLSessionDataTaskProtocol {</pre><pre><em>    //2<br>    </em><strong>func</strong> resume() {}<br>}</pre><p>We create a Mock URLSessionDataTask named “MockURLSessionDataTask” that conforms to URLSessionDataTaskProtocol (1).<br>The required resume method doesn’t do anything.</p><p>Now for the URLSession add this code in the URLSession section:</p><pre><em>//1<br></em><strong>class</strong> MockURLSession: URLSessionProtocol {</pre><pre><em>    //2<br>    </em><strong>var</strong> dataTask = MockURLSessionDataTask()</pre><pre><em>    //3<br>    </em><strong>var</strong> completionHandler: (Data?, URLResponse?, Error?)</pre><pre><em>    //4<br>    </em><strong>init</strong>(completionHandler: (Data?, URLResponse?, Error?)) {<br>        <strong>self</strong>.completionHandler = completionHandler<br>    }</pre><pre>    <em>//5<br>    </em><strong>func</strong> dataTask(with url: URL, completionHandler: <strong>@escaping</strong> (Data?, URLResponse?, Error?) -&gt; Void) -&gt; URLSessionDataTaskProtocol {</pre><pre><em>        //6<br>        </em>completionHandler(<strong>self</strong>.completionHandler.0,<br>                          <strong>self</strong>.completionHandler.1,<br>                          <strong>self</strong>.completionHandler.2)</pre><pre><em>        //7<br>        </em><strong>return</strong> dataTask<br>    }<br>}</pre><p>First we create a Class named “MockURLSession” that conform to URLSessionProtocol (1).<br>Next we declare a property “dataTask” and initialise it as a MockURLSessionDataTask (2).<br>Next we declare another property called “completionHandler” as a Tuple of Data, URLResponse and Error (3). This Tuple is exactly the same as the dataTask response parameter closure, and we will use it to override the dataTask output with our testing values.<br>Next we create an initialiser for the MockURLSession passing the completion values we want to test (4).<br>Next we create the protocol required method dataTask(…) (5).<br>DataTask method when we call it, will call the completion handler closure passing out the test values we have set in the initialisation (6).<br>Finally we will return the mock dataTask (7).</p><p>We complete code of NetworkClient+Mock Swift file will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lc1xpmhFT0_IeS-6P0Hd6g.png" /></figure><h3>4. Testing</h3><p>The time to Test has come … 👻</p><p>The process is:<br>1. Create a Test Json from a real network response<br>2. Load this json inside a Test scenario<br>3. Create the Mock URLSession with the Test response values<br>4. Call the NetworkClient search method<br>5. Test results</p><p>Ok let’s do it!<br>We will start by creating the test json file. In the “URLMockDemoTests” Folder of your project create a new Empty File and save it as Search.json</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*tBdeiCOPh_3OIJuNTs2gxg.png" /></figure><p>Inside this file add a real network response:</p><pre>{<br>&quot;resultCount&quot; : 1,<br>&quot;results&quot; : [<br>    {<br>    &quot;artistId&quot; : 1093102,<br>    &quot;artistName&quot; : &quot;The Prodigy&quot;,<br>    &quot;artistViewUrl&quot; : &quot;https://music.apple.com/...&quot;,<br>    &quot;artworkUrl100&quot; : &quot;https://is4-ssl.mzstatic.com/...jpg&quot;,<br>    &quot;artworkUrl30&quot; : &quot;https://is4-ssl.mzstatic.com/image/...jpg&quot;,<br>    &quot;artworkUrl60&quot; : &quot;https://is4-ssl.mzstatic.com/image/...jpg&quot;,<br>    &quot;collectionCensoredName&quot; : &quot;The Fat of the Land&quot;,<br>    &quot;country&quot; : &quot;USA&quot;,<br>    &quot;currency&quot; : &quot;USD&quot;,<br>    &quot;kind&quot; : &quot;song&quot;,<br>    &quot;previewUrl&quot; : &quot;https://audio-ssl.itunes.apple.com/...m4a&quot;,<br>    &quot;primaryGenreName&quot; : &quot;Electronic&quot;,<br>    &quot;releaseDate&quot; : &quot;1996-11-11T12:00:00Z&quot;,<br>    &quot;trackCount&quot; : 10,<br>    &quot;trackId&quot; : 500162140,<br>    &quot;trackName&quot; : &quot;Breathe&quot;<br>    }<br>]<br>}</pre><blockquote>I have cut the image url paths and removed many key-values from the real response in order for the json to be smaller. If you want you can print the json from the real network call and paste it inside. This will be the real scenario when working with your project.</blockquote><p>Next we will create 2 helper functions. One to help us load the json file and a second to help us create a MockURLSession. OK first go to “URLMockDemoTests” file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*ar__rwJA3qUo09hIJ3_6mw.png" /></figure><p>Delete all pre-created functions and add this code after <strong><em>import</em></strong><em> XCTest</em></p><pre><strong>@testable</strong> <strong>import</strong> URLMockDemo</pre><p>The file should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bi-cYUb_1t_JX8O-ejp8Ag.png" /></figure><p>Ok let’s create the json loader helper function</p><pre><strong>private</strong> <strong>func</strong> loadJsonData(file: String) -&gt; Data? {</pre><pre><em>    //1<br>    </em><strong>if</strong> <strong>let</strong> jsonFilePath = Bundle(for: type(of:  <strong>self</strong>)).path(forResource: file, ofType: &quot;json&quot;) {<br>        <strong>let</strong> jsonFileURL = URL(fileURLWithPath: jsonFilePath)</pre><pre><em>        //2<br>        </em><strong>if</strong> <strong>let</strong> jsonData = <strong>try</strong>? Data(contentsOf: jsonFileURL) {<br>            <strong>return</strong> jsonData<br>        }<br>    }</pre><pre><em>    //3<br>    </em><strong>return</strong> <strong>nil<br></strong>}</pre><p>This function take a String as parameter and return optional Data.<br>First we get the json file’s URL from the Test Bundle (1).<br>Then we create Data from the file (2), And if the Data creation was successful we return the Data, otherwise we return nil (3).</p><p>Now let’s create the second helper method, the one that will create the Mock URlSession</p><pre><strong>private</strong> <strong>func</strong> createMockSession(fromJsonFile file: String,<br>                        andStatusCode code: Int,<br>                        andError error: Error?) -&gt; MockURLSession? {</pre><pre><em><br>    //1<br>    </em><strong>let</strong> data = loadJsonData(file: file)</pre><pre><em>    //2<br>    </em><strong>let</strong> response = HTTPURLResponse(url: URL(string: &quot;TestUrl&quot;)!, statusCode: code, httpVersion: <strong>nil</strong>, headerFields: <strong>nil</strong>)</pre><pre><em>    //3<br>    </em><strong>return</strong> MockURLSession(completionHandler: (data, response, error))<br>}</pre><p>This method returns a MockURLSession from a given json file, with a specific network return status code and a specific network return error. As you can see with the Mock version of the URLSession we can test all network scenarios, from specific status codes to specific errors 💪.</p><p>First we create the Json Data using the first helper function we created (1).<br>Next we create our custom HTTPURLResponse passing a dummy URL and the status code we want to test (2). Last we return a MockURLSession Class initialised with a completion that returns the json Data, the custom Response and the error parameter (3).</p><p>As we can see we feed the MockUrlSession with the test data we want to test. When the dataTask will call “resume” it will not make a real network call but instead will return to us the Test data we fed it!</p><p>Ok now let’s create our test scenario methods</p><pre>//1<strong><br>var</strong> sut: NetworkClient!</pre><pre>//2<br><strong>var</strong> mockSession: MockURLSession!</pre><pre>//3<br><strong>override</strong> <strong>func</strong> tearDown() {<br>    sut = <strong>nil<br>    </strong>mockSession = <strong>nil<br>    super</strong>.tearDown()<br>}</pre><p>We declare a property called “sut” (Subject under Test) as NetworkClient Type (1), After all we test the NetworkClient Class. Another property named “mockSession” as MockURLSession Type (2), and we override the tearDown test method to free our properties (3). The file should like like this until now</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IIndf_bDBbhnPe_EbAoOIg.png" /></figure><p>Ok the final part is to create some Test Cases. Add these methods:</p><pre>//1<strong><br>func</strong> testNetworkClient_successResult() {</pre><pre>    mockSession = createMockSession(fromJsonFile: &quot;Search&quot;,<br>andStatusCode: 200, andError: <strong>nil</strong>)<br>    sut = NetworkClient(withSession: mockSession)</pre><pre>    sut.searchItunes(url: URL(string: &quot;TestUrl&quot;)!) { (trackStore, errorMessage) <strong>in</strong></pre><pre>        XCTAssertNotNil(trackStore)<br>        XCTAssertNil(errorMessage)<br>        XCTAssertTrue(trackStore!.results.count == 1)</pre><pre><strong>        let</strong> track = trackStore!.results.first!<br>        XCTAssertTrue(track.trackName == &quot;Breathe&quot;)<br>    }<br>}</pre><pre>//2<strong><br>func</strong> testNetworkClient_404Result() {<br>    mockSession = createMockSession(fromJsonFile: &quot;Search&quot;, andStatusCode: 404, andError: <strong>nil</strong>)<br>    sut = NetworkClient(withSession: mockSession)</pre><pre>    sut.searchItunes(url: URL(string: &quot;TestUrl&quot;)!) { (trackStore, errorMessage) <strong>in<br>        </strong>XCTAssertNotNil(errorMessage)<br>        XCTAssertNil(trackStore)<br>        XCTAssertTrue(errorMessage == &quot;Bad Url&quot;)<br>    }<br>}</pre><pre>//3<strong><br>func</strong> testNetworkClient_NoData() {<br>    mockSession = createMockSession(fromJsonFile: &quot;A&quot;, andStatusCode: 500, andError: <strong>nil</strong>)<br>    sut = NetworkClient(withSession: mockSession)</pre><pre>    sut.searchItunes(url: URL(string: &quot;TestUrl&quot;)!) { (trackStore, errorMessage) <strong>in<br>        </strong>XCTAssertNotNil(errorMessage)<br>        XCTAssertNil(trackStore)<br>        XCTAssertTrue(errorMessage == &quot;No Data&quot;)<br>    }<br>}</pre><pre>//4<strong><br>func</strong> testNetworkClient_AnotherStatusCode() {<br>    mockSession = createMockSession(fromJsonFile: &quot;Search&quot;, andStatusCode: 401, andError: <strong>nil</strong>)<br>    sut = NetworkClient(withSession: mockSession)</pre><pre>    sut.searchItunes(url: URL(string: &quot;TestUrl&quot;)!) { (trackStore, errorMessage) <strong>in<br>        </strong>XCTAssertNotNil(errorMessage)<br>        XCTAssertNil(trackStore)<br>        XCTAssertTrue(errorMessage == &quot;statusCode: 401&quot;)<br>    }<br>}</pre><p>In the First Test case we Test a successful callback. We read from a valid Json file, with status code 200. We check the name of the track (1).</p><p>In the second Test case we Test a 404 status code callback. We set the status code to be 404 and we check the errorMessage to be “Bad Url” (2).</p><p>In the third Test case we Test an invalid Json that will return no data. We check the errorMessage to be “No Data” (3).</p><p>In the fourth Test case we test a non handled status code. 401. We check the errorMessage to be “statusCode: 401” (4).</p><p>If we check our NetworkClient Test coverage will be 98%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nAw_c10LjBb2slGW-GtFig.png" /></figure><p>Mocking and Testing is a time consuming process BUT it will save you when working with large teams and refactors. Just spend this time to do it!</p><p>You can download the Demo from GitHub<br><a href="https://github.com/Valsamis/URLMockDemo">https://github.com/Valsamis/URLMockDemo</a></p><p>See you in the next Story.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6553ecdd3b81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Method swizzling in Swift]]></title>
            <link>https://medium.com/@valsamiselmaliotis/method-swizzling-in-swift-2ff25926569d?source=rss-3caea706aa38------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ff25926569d</guid>
            <category><![CDATA[swizzle]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[method-swizzling]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swizzling]]></category>
            <dc:creator><![CDATA[Valsamis Elmaliotis]]></dc:creator>
            <pubDate>Tue, 08 Oct 2019 13:47:31 GMT</pubDate>
            <atom:updated>2019-10-08T13:47:31.121Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this story we will see how we can change a method’s implementation in RunTime.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lXi5aKeSGhCXqoF1" /><figcaption>Photo by <a href="https://unsplash.com/@shemul?utm_source=medium&amp;utm_medium=referral">Shahadat Shemul</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Objective-C runtime is powerful enough to give us the tools to change a method’s implementation in runtime through <strong>Method swizzling</strong>.</p><p>Using <strong>Method swizzling</strong> we change the implementation of an existing selector at <strong>runtime</strong>.</p><p>Let’s see how we can use it in Swift. Our class must inherit from <strong>NSObject</strong> in order to use Objective-C runtime.</p><pre><strong>class</strong> Object: NSObject {}</pre><p>Our object Class will have a method called printResult. printResult method must be <strong>dynamic</strong> because we will change it at <strong>runtime</strong>.<br>For now when we call it will simply prints “Original Result”</p><pre><strong>class</strong> Object: NSObject {</pre><pre><strong>    @objc</strong> <strong>dynamic</strong> <strong>func</strong> printResult() {<br>        print(&quot;Original Result&quot;)<br>    }<br>}</pre><p>Lets create the method now, that we want to replace the implementation of printResult’s method</p><pre><strong>class</strong> Object: NSObject {</pre><pre><strong>    @objc</strong> <strong>dynamic</strong> <strong>func</strong> printResult() {<br>        print(&quot;Original Result&quot;)<br>    }</pre><pre><strong>    @objc</strong> <strong>dynamic</strong> <strong>private</strong> <strong>func</strong> swizzledResult() {<br>        print(&quot;Swizzled Result&quot;)<br>    }<br>}</pre><p>swizzledResult method holds the override implementation code. We declare it also as <strong>dynamic</strong> and as private because we do not want to be accessed form another source.</p><p>So what is left is to create the method that when we call, will change implementations.</p><pre><strong>class</strong> Object: NSObject {</pre><pre><strong>    @objc</strong> <strong>dynamic</strong> <strong>func</strong> printResult() {<br>        print(&quot;Original Result&quot;)<br>    }</pre><pre><strong>    @objc</strong> <strong>dynamic</strong> <strong>private</strong> <strong>func</strong> swizzledResult() {<br>        print(&quot;Swizzled Result&quot;)<br>    }</pre><pre><strong>    func</strong> swizzle() {</pre><pre>        //1<br>        <strong>let</strong> originalClass = Object.<strong>self</strong></pre><pre><strong>        </strong>//2<strong><br>        let</strong> printResult = class_getInstanceMethod(originalClass,  <strong>#selector</strong>(Object.printResult))</pre><pre>        //3<br>        <strong>let</strong> swizzledResult = class_getInstanceMethod(originalClass, <strong>#selector</strong>(Object.swizzledResult))</pre><pre>        //4<br>        method_exchangeImplementations(printResult!, swizzledResult!)</pre><pre>    }<br>}</pre><p>We create a method called swizzle.<br>First we need to get the <strong>Class Instance Type</strong> (1)<br>Then we need the <strong>Instance Method</strong> of both printResult and swizzledResult methods (2,3)<br>Finally we have to change the printResult method implementation with the implementation of swizzledResult method by calling <strong>method_exchangeImplementations</strong>. (4)</p><p>Ok let’s test it out:</p><pre><strong>let</strong> object = Object()<br>object.printResult()</pre><p>We create an Object Instance and call printResult. As expected we see in the console:</p><pre><strong>Original Result</strong></pre><p>Now let’s call the magic swizzle method and try again</p><pre>object.swizzle()<br>object.printResult()</pre><p>WOW!!! now the see in the console:</p><pre><strong>Swizzled Result</strong></pre><p>We have successfully <strong>Swizzled</strong> methods!</p><p>See you in the next story.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ff25926569d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boxing technique in Swift]]></title>
            <link>https://medium.com/@valsamiselmaliotis/boxing-technique-in-swift-b12a28a29132?source=rss-3caea706aa38------2</link>
            <guid isPermaLink="false">https://medium.com/p/b12a28a29132</guid>
            <category><![CDATA[class]]></category>
            <category><![CDATA[struct]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[boxing]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Valsamis Elmaliotis]]></dc:creator>
            <pubDate>Wed, 02 Oct 2019 11:23:45 GMT</pubDate>
            <atom:updated>2019-10-02T11:23:45.427Z</atom:updated>
            <content:encoded><![CDATA[<h4>Use Boxing technique to share the Instance of a Struct</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aW2t9daNmqQXxO4L" /><figcaption>Photo by <a href="https://unsplash.com/@erdaest?utm_source=medium&amp;utm_medium=referral">Erda Estremera</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As we know <strong>Structs</strong> in Swift are <strong>Value Type Objects</strong>.<br>Meaning when you assign or pass a <strong>Struct</strong> object to another property or argument it creates a <strong>copy</strong> of the original one.</p><p>Let’s test it out:</p><pre>//1<strong><br>struct</strong> User {<br>    <strong>var</strong> name: String<br>}</pre><pre>//2<strong><br>var</strong> user1 = User(name: &quot;Mark&quot;)<br><strong>var</strong> user2 = user1</pre><pre>//3<br>user2.name = &quot;John&quot;</pre><pre>print(&quot;user1 name: \(user1.name)&quot;)<br>print(&quot;user2 name: \(user2.name)&quot;)</pre><p>We create a <strong>Struct</strong> named User (1).</p><p>(2)<br>We define a property user1 as <strong>User</strong> with name Mark.<br>Then we define a property user2 equal to user1.</p><p>We change user2 name to John (3)</p><p>The print result is:</p><pre><strong>user1 name: Mark<br>user2 name: John</strong></pre><p>As we can see only user2 name has changed to John even if user2 property was created from user1. This is because a <strong>copy</strong> of user1 is created and passed to user2 value.</p><p>Sometimes we may want to change this behaviour.<br>In order to accomplish it we have to use a technique called <strong>Boxing</strong>.<br>We will <strong>wrap</strong> the Struct instance inside a <strong>Class</strong> instance and share the Class Instance to be changed from other resources.</p><p>Let’s do it:</p><pre>//1<br><strong>final</strong> <strong>class</strong> UserBox {<br>    <strong>var</strong> user: User</pre><pre><strong>    init</strong>(user: User) {<br>        <strong>self</strong>.user = user<br>    }<br>}</pre><pre>//2<br><strong>var</strong> user1 = User(name: &quot;Mark&quot;)</pre><pre>//3<br><strong>var</strong> userBox = UserBox(user: user1)</pre><p>First we create a new <strong>Class</strong> named <strong>UserBox</strong> (1).<br><strong>UserBox</strong> has 1 property of type <strong>User</strong> that been set from init method.</p><p>Now lets say we have an instance of user1 that we want to share (2)</p><p>We will wrap user1 inside userBox. (3)</p><p>Now lets pass this instance:</p><pre>//1<strong><br>var</strong> userBox2 = userBox</pre><pre>//2<br>userBox2.user.name = &quot;Nick&quot;</pre><pre>print(&quot;userBox1 name: \(userBox.user.name)&quot;)<br>print(&quot;userBox2 name: \(userBox2.user.name)&quot;)</pre><p>We define a property userBox2 to be equal to userBox (1).<br>Then we change that name to Nick (2). As you can see to access the <strong>User</strong> we use the user property of <strong>UserBox</strong>.</p><p>Now the magic happens… The print result is:</p><pre><strong>userBox1 name: Nick<br>userBox2 name: Nick</strong></pre><p>As we can see both userBox1 and userBox2 user name property has changed.</p><p>See you in the next story!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b12a28a29132" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Initialize Class from Type in Swift]]></title>
            <link>https://medium.com/@valsamiselmaliotis/initialize-class-from-type-in-swift-c1aa1ccbb249?source=rss-3caea706aa38------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1aa1ccbb249</guid>
            <category><![CDATA[protocol]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[type]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[class]]></category>
            <dc:creator><![CDATA[Valsamis Elmaliotis]]></dc:creator>
            <pubDate>Tue, 01 Oct 2019 14:33:57 GMT</pubDate>
            <atom:updated>2019-10-01T14:33:57.206Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this story we will see how we can initialize a Class from it’s Type</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rjbCH6p3DF8P5_8H" /><figcaption>Photo by <a href="https://unsplash.com/@clemhlrdt?utm_source=medium&amp;utm_medium=referral">Clément H</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s say we have a <strong>Class</strong>:</p><pre><strong>class</strong> MyClass {}</pre><p>And we want to create an <strong>Instance</strong> from it’s <strong>Type</strong>!</p><p>Let’s create a helper generic function:</p><pre><strong>func</strong> initializeObject&lt;T&gt;(fromType type: T.Type) -&gt; T {</pre><pre>    return ???</pre><pre>}</pre><p>This generic function take as an argument an <strong>Instance Type</strong> and return an <strong>Instance</strong>.<br>We can call it like this:</p><pre><strong>var</strong> object1 = initializeObject(fromType: MyClass.<strong>self</strong>)</pre><p>But what should this function return?</p><pre><strong>func</strong> initializeObject&lt;T&gt;(fromType type: T.Type) -&gt; T {</pre><pre>    //1<br>    return T.init() <em>//error</em></pre><pre>}</pre><p>We cant use <strong>init()</strong> because we have not set it as required in our <strong>Class</strong> implementation. So let’s add it, update MyClass code:</p><pre><strong>class</strong> MyClass {</pre><pre><strong>    required</strong> <strong>init</strong>() {}</pre><pre>}</pre><p>Now init() from <strong>Type</strong> will work fine but because our function takes a generic argument, <strong>T</strong> does not know about init method. To overcome this issue we can create a <strong>protocol</strong>:</p><pre><strong>protocol</strong> Initializable {</pre><pre><strong>    //1<br>    init</strong>()</pre><pre>}</pre><p>We call it Initializable and as mandatory method we declare init().<br>Now let’s make MyClass conform to this protocol:</p><pre><strong>class</strong> MyClass: Initializable {</pre><pre><strong>    required</strong> <strong>init</strong>() {}</pre><pre>}</pre><p>Now the helper function does not return an error</p><pre><strong>func</strong> initializeObject&lt;T: Initializable&gt;(fromType type: T.Type) -&gt; T {</pre><pre><strong>    return</strong> T.init() //No Error</pre><pre>}</pre><p>So let’s create some MyClass instances:</p><pre><strong>var</strong> object1 = initializeObject(fromType: MyClass.<strong>self</strong>)<br><strong>var</strong> object2 = initializeObject(fromType: MyClass.<strong>self</strong>)</pre><p>We have successfully used Initializable protocol with our generic function and now we can create any Class Instances :)</p><p>To confirm that object1 and object2 are separate instances we can print the memory addresses:</p><pre>withUnsafePointer(to: &amp;object1) {</pre><pre>    print(&quot;object1 address: \($0)&quot;)</pre><pre>}</pre><pre>withUnsafePointer(to: &amp;object2) {</pre><pre>    print(&quot;object2 address: \($0)&quot;)</pre><pre>}</pre><pre>//prints:<br><strong>object1 address: 0x000000012274c610</strong></pre><pre><strong>object2 address: 0x000000012274c618</strong></pre><p>See you in the next story!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1aa1ccbb249" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Removing Specific Type from an Array in Swift]]></title>
            <link>https://medium.com/@valsamiselmaliotis/removing-specific-type-from-an-array-in-swift-4d45f40eebc5?source=rss-3caea706aa38------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d45f40eebc5</guid>
            <category><![CDATA[type]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[remove]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Valsamis Elmaliotis]]></dc:creator>
            <pubDate>Tue, 01 Oct 2019 09:45:22 GMT</pubDate>
            <atom:updated>2019-10-01T09:45:22.114Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uIh4ta720KprwR-6" /><figcaption>Photo by <a href="https://unsplash.com/@bugsster?utm_source=medium&amp;utm_medium=referral">Taras Shypka</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine that you have an array like this:</p><pre>let array: [Any] = [nick, john, nick, “String”, 3]</pre><p>and you want to remove all elements of a specific Type! What will we do?</p><p>Let’s create an example…</p><pre><strong>class</strong> Nick {}</pre><pre><strong>struct</strong> John {}</pre><pre><strong>let</strong> nick = Nick()</pre><pre><strong>let</strong> john = John()</pre><pre><strong>let</strong> array: [<strong>Any</strong>] = [nick, john, nick, &quot;String&quot;, 3, &quot;AnotherString&quot;]</pre><pre>print(array)</pre><p>In this example we have a Class <strong>Nick</strong> and a Struct <strong>John</strong>.</p><p>Finally our array contains 2 <strong>Nick</strong> objects, 1 <strong>John</strong>, 2 <strong>Strings</strong> and 1 <strong>Integer</strong>.</p><p>The print result is:</p><pre><strong>[__lldb_expr_12.Nick, __lldb_expr_12.John(), __lldb_expr_12.Nick, &quot;String&quot;, 3, &quot;AnotherString&quot;]</strong></pre><p>Let’s say we want to remove all <strong>nick</strong> objects form this array.</p><p>Create a helper function:</p><pre><strong>func</strong> removeType(formArray array: [<strong>Any</strong>], ofType type: <strong>Any</strong>.Type) -&gt; [<strong>Any</strong>] {</pre><pre>    //1</pre><pre><strong>    let</strong> filteredArray = array.filter { item <strong>in<br>        //2</strong></pre><pre><strong>        let</strong> mirror = Mirror(reflecting: item)<br>        //3</pre><pre><strong>        return</strong> mirror.subjectType != type</pre><pre>    }<br>    //4</pre><pre><strong>    return</strong> filteredArray</pre><pre>}</pre><p>Our function takes as argument the array we need to modify and the type we want to remove. Finally return the modified array.</p><p>To achieve our result we need to filter the original array. (1)</p><p>In the filtering block we want to <strong>mirror</strong> the active element (2) and get it’s <strong>subjectType</strong> (3). If the <strong>subjectType</strong> is different than the <strong>type</strong> we want to remove, we keep the item.</p><p>Finally we return the filtered array (4)</p><p>Let’s call this function to remove all <strong>Nick</strong> objects</p><pre><strong>var</strong> filteredArray = removeType(formArray: array, ofType: Nick.<strong>self</strong>)</pre><pre>print(filteredArray)</pre><p>We pass as type argument the <strong>Type</strong> of <strong>Nick</strong> object.</p><p>The print result is:</p><pre><strong>[__lldb_expr_16.John(), &quot;String&quot;, 3, &quot;AnotherString&quot;]</strong></pre><p>As we can see all <strong>Nick</strong> objects are removed.</p><p>If we wanted to remove all <strong>Strings</strong> we could use:</p><pre><strong>var</strong> filteredArray = removeType(formArray: array, ofType: String.<strong>self</strong>)</pre><pre>print(filteredArray)</pre><p>The print result is:</p><pre><strong>[__lldb_expr_1.Nick, __lldb_expr_1.John(), __lldb_expr_1.Nick, 3]</strong></pre><p>See you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d45f40eebc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>