<?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 Tim Platt on Medium]]></title>
        <description><![CDATA[Stories by Tim Platt on Medium]]></description>
        <link>https://medium.com/@timothydplatt?source=rss-296dc96c9045------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_X2O2JzGR_srAOqargiLKw.jpeg</url>
            <title>Stories by Tim Platt on Medium</title>
            <link>https://medium.com/@timothydplatt?source=rss-296dc96c9045------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 18:35:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@timothydplatt/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[How I Taught Myself to Code - A Credit Card Repayment Calculator]]></title>
            <link>https://medium.com/@timothydplatt/how-i-taught-myself-to-code-a-credit-card-repayment-calculator-c9986b58b635?source=rss-296dc96c9045------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9986b58b635</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[apps]]></category>
            <dc:creator><![CDATA[Tim Platt]]></dc:creator>
            <pubDate>Fri, 18 Jan 2019 10:23:47 GMT</pubDate>
            <atom:updated>2019-02-07T17:34:24.808Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Lending in the UK is at its all time highest. The average consumer credit borrowing stood at <a href="https://themoneycharity.org.uk/money-statistics/">£4,140 per adult</a> (15% of average earnings) as of Dec 2018. Each day 12 homes are re-possessed, 273 people are declared bankrupt and 3001 county court judgements are issued. An increasing number of people are reaching out to debt charities such as <a href="https://themoneycharity.org.uk/">The Money Charity</a> or <a href="https://www.stepchange.org/">Step Change</a> as UK adults struggle to make ends meet.</p><p>Unfortunately, it’s those that are most vulnerable that suffer most; people with the poorest credit histories are forced to borrow at higher interest rates. Additionally, many individuals are simply not equipped with the financial tools and education needed to succeed with credit. People will miss repayments, fail to consolidate debts, not understand the APR rate that they’re accepting etc and their financial situation can snowball very quickly.</p><p>The story of <a href="https://www.bbc.co.uk/news/resources/idt-sh/How_debt_kills">Jerome Rogers</a> had a profound impact on me. It reinforced how important it is to provide support for those navigating financial difficulty.</p><h3>The Shortcomings of Minimum Repayments</h3><p>My work has focused on addressing one specific educational gap with regards to credit lending. In short, I want to equip credit card consumers with the knowledge that repaying only a little more each month can significantly shorten how long it takes to clear their balance and the amount of interest they will pay.</p><p>A large % of UK credit card holders only make the minimum payment on their credit cards each month and it’s not necessarily a bad thing. Firstly, making the minimum repayment will ensure you don’t incur late payment fees and will allow you to clear at least your interest. Secondly, it’s perhaps all a consumer can afford and it gives them flexibility to pay a small amount while low on cash.</p><p>However, many credit card consumer don’t realise that they should strive to pay at least their minimum each month, but ideally a little but more. Why? It essentially boils down to the fact the minimum payment is calculated as . percentage of your balance i.e. “<em>the greater of 1% of your balance + interest or £5</em>”. Thus, as your balance decreases so does your minimum payment, which means it will take longer to repay your debts and cost your more to pay back what you owe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/0*OK5kKQJ54eoVqCTd.gif" /></figure><p>Above is an example that takes a credit balance of £2,292 and an interest rate of 17.91% APR. It would take 25 years and 3 months to repay a this credit card paying only the minimum vs. 5 years and 3 months if we paid the first months minimum payment amount each month.</p><h3>A Solution to Encourage Bigger Repayments</h3><p>I’ve developed an app that allows people to visually calculate how much difference paying a fixed amount each month could make to their credit card repayment time and the interest they will pay. The app can be seen below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FYuTFtwKXdSw%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DYuTFtwKXdSw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FYuTFtwKXdSw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/15b5800e799efd6f582437dc7b35b12a/href">https://medium.com/media/15b5800e799efd6f582437dc7b35b12a/href</a></iframe><p>The app’s information architecture is pretty straight forward (on paper). The first screen is the ‘landing screen’ and its purpose is to introduce the app to the user. This app is particularly suited to people who are ‘paying off’ their debt i.e. repaying their credit cards minimum payment on time each month (or some fixed amount) but not spending on that credit card. The app naturally is unable to take into account customers spend, fees etc. It’s aim is to give people an indicative idea of the impact paying £X vs. £Y per month, will have on their repayment time and the interest payable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rl8xqFTouPLcWpdsWjzCzg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qwN01mXARn2sDZg3CqOPXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXiFfZCNw2FE8EdeCBRvHQ.png" /></figure><p>Next we have a series of screens that ask the user to provide 3 pieces of information: their credit card balance, APR and information about how their minimum payment is calculated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jv5kRjemHRalmsUK2TAL6w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7vM9kF27phdDCF919kHj3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2M9htQBTtkCbonjwkg2Pdw.png" /></figure><p>Finally, I use this information display an interactive visualisation that tells users how long it will take to pay off their balance and how much interest they will pay (represented by a 360° solid ring) if they only pay their minimum. The ring then automatically transforms into an arc, which represents the time it would take to clear the credit card balance if the user paid their first min payment amount each and every month. It makes a staggering difference huh? The user can then increment the fixed monthly payment amount to see what impact that will have on repayment time and interest incurred.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rl8xqFTouPLcWpdsWjzCzg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PlASBa_2qSJjMAkoyHH-kA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXiFfZCNw2FE8EdeCBRvHQ.png" /></figure><p>The tool is relatively simple but for me it’s power lays in it’s ability to visually illustrate that a small change (paying a little bit more) can have a significant impact (clear credit card balance more quickly and incur less interest). People also like to work towards an end date i.e. if I can afford £X each month, when well I be debt free by? If I want to pay my credit card off in the next 3 years, what do I need to pay each month? Etc.</p><h3>How Did I Develop This Solution?</h3><p>OK, so let’s step through the implementation screen by screen.</p><h4>Landing Screen</h4><p>For the landing screen I used a framework called <a href="https://github.com/SvenTiigi/WhatsNewKit">WhatsNewKit</a> as recommended by a friend. The framework provides an easy to modify boilerplate “What’s New” screen, which I’ve used instead to introduce the app each time the user launches it.</p><p>I actually found the framework quite painful to use; installation was difficult, configuring button actions was tedious, customising properties i.e. alignment of screen text, simply didn’t work! Etc. The framework definitely looks great but it’s not a framework I’d readily use again or recommend to someone with my level of experience.</p><h4>Capturing User Input</h4><p>The next step was to capture the user input, which was surprisingly difficult! I experienced two challenges; validating the user input and formatting valid input correctly.</p><p><strong>Validating User Input<br></strong>Firstly, let’s take the APR input screen as an example. In order to validate user input we can use the UITextField’s delegate method textField(<strong>_</strong> textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String). This method is basically called each time a user changes the content of a UITextField. As a developer we get to know what UITextField was changed, the range of characters to be replaced and the replacement string for that range of characters. In the body of the delegate method we can decide whether we we reject the textfield input (return false) or accept it (return true).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea2f4dd1c06a28857d50258da6096d32/href">https://medium.com/media/ea2f4dd1c06a28857d50258da6096d32/href</a></iframe><p>In the above we check the user input is numeric, that the number of dots is less than or equal to 1 and the number of both decimal and integer digits is less than or equal to 2. If the input meets this criteria we could return true i.e. accept the input, however we instead all the updateAPRTextField() method as we need to add a % symbol, update the cursor position and check if we should enable the ‘next’ button:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/335a027c928110c5366fc38f075f80ee/href">https://medium.com/media/335a027c928110c5366fc38f075f80ee/href</a></iframe><p><strong>Formatting User Input<br></strong>In the above I do some formatting i.e. adding the % symbol and moving the cursor, however it’s not very clean code and it’s a lot of ‘fudging’.</p><p>Let’s take the balance input screen as an example of how to format user input in iOS. I needed to style the text field and keyboard the correct way i.e. the £ symbol is always left aligned, numbers are inputted right to left, a decimal point and comma insert themselves in the correct place etc.</p><p>This should be handled by subclassing UITextField and customising it for your own needs as. The solution to creating a UITextField that formats input as currency is shown in the code below. In honesty, a lot of the below came from scouring StackOverflow and it took me quite some time to understand what was going on. Don’t be afraid though, the below is complex and a lot of people, even on StackOverflow, weren’t super clear on UITextFields.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/289e399334bbc18e660ba59551c403e9/href">https://medium.com/media/289e399334bbc18e660ba59551c403e9/href</a></iframe><h4>Minimum Repayment Calculation</h4><p>OK, so we’ve captured valid user input and we now have what we need to calculate how long it will take the repay to clear the balance and the total amount of interest that will be paid. The code is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/046dea63d4dc0ff76269a4d152891f1f/href">https://medium.com/media/046dea63d4dc0ff76269a4d152891f1f/href</a></iframe><p>The code essentially does the following:</p><ul><li>Casts all of the user inputs into Decimal type. Decimal is used over Double because it provides greater base 10 precision. <a href="https://medium.com/swift-programming/creating-a-money-type-in-swift-3b060fb762ed">Great article on this</a>.</li><li>Create necessary variables and constants for performing calculation and storing return values.</li><li>While the balance remaining is greater than 0, calculate the minimum payment and what amount of this is interest.</li><li>Check if the minimum payment amount is greater than either a fixed amount given by the user or a percentage of balance only amount given by the user (sometimes minimum payments are just X% of the balance and don’t include interest).</li><li>Calculate the principal payment amount i.e. the minimum payment excluding interest. Deduct this from the remaining balance if it’s less than the remaining balance, else deduct the remaining balance.</li><li>Repeat steps 3–5 if the remaining balance is greater than 0.</li><li>Return the time it takes to pay off the credit card, the interest the user would pay and for each month return the min payment amount and remaining balance.</li></ul><p>I also coded a fixed payment calculation so that users could compare a fixed amount each month against paying their minimum payment each month. As you could imagine, it’s similar to the above but much simpler.</p><h4>Creating an Interactive Visualisation</h4><p>I show the repayment time and cumulative interest visually as a ring using an awesome framework called <a href="https://github.com/luispadron/UICircularProgressRing">UICircularProgressRing</a>. I spent a long time trying to find a good framework fit for the task at hand and even tried to build my own visualisation from scratch (I’m still determined!), but this framework worked a charm and was super easy to use.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F9x30fcOwokXAabpQxs%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2F9x30fcOwokXAabpQxs&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F9x30fcOwokXAabpQxs%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="940" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e39f720c5bc3b358e514e3cc27d3ee4/href">https://medium.com/media/4e39f720c5bc3b358e514e3cc27d3ee4/href</a></iframe><p>The first thing I do is initialise the progress rings properties i.e. maximum value, ring width, ring style etc. At this point, nothing is drawn on the screen, I’m simply defining the blue print.</p><p>The next thing is to set the progress rings initial value to be the maximum value i.e. the time it would take to pay the credit card balance if the user only pays their minimum. This is the max value as the app doesn’t allow the user to pay less than their minimum.</p><p>Finally, I set the ring to have a new value equivalent to the amount of time it would take the user to clear their debt if their payed their rounded up first minimum payment amount each month. The animation and ‘dot style’ effect is handle by the framework. The result is what I consider a very powerful visualisation which really brings to light what an impact paying a little more can have on a consumers repayment times.</p><p>OK, so let’s look at the Swift code behind this. Firstly, as mentioned, we define the properties of the progress ring object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0d397ce05aaa132ef725984b4eb1a64/href">https://medium.com/media/a0d397ce05aaa132ef725984b4eb1a64/href</a></iframe><p>We then set the progress ring to be a full circle i.e. to equal the maximum value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdcca63814b14b4113ecf3b26beea65f/href">https://medium.com/media/bdcca63814b14b4113ecf3b26beea65f/href</a></iframe><p>Finally, we have a method that updates the progress ring and information text each time the user enters a fixed amount or uses the ‘+’ or ‘-’ buttons to increment or decrement the repayment amount.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9cc5c37c579b047bff8d9244980f4b7/href">https://medium.com/media/c9cc5c37c579b047bff8d9244980f4b7/href</a></iframe><h3>What Were The Challenges?</h3><p>As I’m finding is the case with iOS, there’s a lot of things that you’d expect to be simple that are surprisingly difficult. The main thing though is that I’m learning! Even now, writing this blog, I’m looking at my code and realising how poorly written it is (the user input variables should really be properties of a ‘credit card debt’ object or something) but I think being a great coder is just a case of persistence and practice. So the tricky bits…</p><h4>Arithmetic Precision</h4><blockquote>Humans count things using base 10; computers find it easier to count using base 2 (1 and 0). Integers translate from base 10 to base 2 just fine. The problem arises with fractions. Not every base 10 fraction can be represented accurately when using base 2.</blockquote><p>Ok, so how does this manifest itself as a problem in programming. Well look at the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*ENHtMMCLDcVagRS1T78dEQ.png" /></figure><p>The developer keeps a running tally. They add 0.01 (using Floats) in a loop 100 times, resulting in a sum of 1. However, the developer doesn’t get 1 due to the fact that they’re using a Float (binary type), which can’t accurately represent the value 0.01. We thus have a loss of precision.</p><p>NSDecimalNumber is a Swift Type that allows us to circumvent these precision issues, but is not as well documented and widely used as Float and Double.</p><h4>Keyboard Handling</h4><p>There’s two things stressful about keyboards in iOS: adjusting content relative to the keyboard and adding an accessory view if desired.</p><p>So showing a keyboard is simple, you basically just need to add a UITextField and when that field is touched the operating system automatically shows the keyboard (i.e. designates it as first responder). However, you need to think about adjusting your content if the keyboard obscures the UITextField from the use for example. To do this we need to register our UIViewController to the Notification Centre to receive certain notifications:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5fc0bb196ea31b4c3f59509869f32e6/href">https://medium.com/media/d5fc0bb196ea31b4c3f59509869f32e6/href</a></iframe><p>We then need to write to functions that handle the Notification object passed to them when a keyboard shows or hides. We can get the keyboard size from this Notification object and adjust the screens position accordingly (or the offset of a scrollview if using one):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e013db49ba95809c9b314812b840409/href">https://medium.com/media/1e013db49ba95809c9b314812b840409/href</a></iframe><p>A lot of this was new to me, hence why I found it challenging, specifically the #selector syntax, which in all honesty I’m still not completely comfortable with.</p><h4>UITextField Delegate Methods</h4><p>I battled for hours with performing input validation using UITextFields delegate methods. It’s likely that any time you take user input, you’ll want to perform client side validation to ensure that the user only enters valid input, but it can be quite complex.</p><p>I also foolishly tried to change the replacementString parameter of the delegate method (i.e. the users input). However, you can’t do… all you can do is return a Boolean value i.e. do you want to accept the users input or not. For hours I couldn’t figure our how to change the users input (to append a % symbol).</p><p>It was only after much Googling that I realise you can just call another method from within the UITextField’s delegate method and update the textfield with the tweaked user input from there (and only ever return false from UITextField’s delegate method).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2cee7925bba7a721e621a7c5d9c33d6/href">https://medium.com/media/b2cee7925bba7a721e621a7c5d9c33d6/href</a></iframe><h3>What Were The Highlights?</h3><p>The entire process of having an idea and watching it come to life is a highlight. There’s so many frustrating challenges you encounter when developing an app and as an equal amount of mini triumphs when you overcome them. The only part of the journey that’s bittersweet is that I wish I’d jumped into writing code earlier in my life and perhaps have pursued a career in it.</p><p>The icing on the cake however has been watching people actually take the app for a spin and be blown away by the relationship between what your repay and how quickly you clear your debt/the interest you incur. To see people benefit from your creations in the ways you intended is awesome.</p><h3>Summary</h3><p>There is a single intrinsic motivation behind why I’ve learned to develop iOS apps; quite simply I want to create technology that improves peoples lives and helps make life easier for people. It’s cheesy and perhaps naive, but it gives me purpose and there’s no better motivator than sense of purpose. This is the reason why all of my apps are free; it’s not about the money ❤️.</p><p>If you’re struggling with debt, please seek help and don’t bear the burden alone:</p><p><a href="https://www.stepchange.org/">Step Change</a>: <strong>0800 138 1111</strong></p><p><a href="https://www.nationaldebtline.org/">National Debt Line</a>: <strong>0808 808 4000</strong></p><p><a href="https://themoneycharity.org.uk/">The Money Charity</a>: <strong>020 7062 8933</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9986b58b635" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to Initialisation - Swift 4]]></title>
            <link>https://medium.com/@timothydplatt/a-guide-to-initialisation-swift-4-ec299c546de7?source=rss-296dc96c9045------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec299c546de7</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Tim Platt]]></dc:creator>
            <pubDate>Wed, 12 Dec 2018 12:51:36 GMT</pubDate>
            <atom:updated>2018-12-12T15:36:40.997Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Initialisation?</h3><h4>Initialisation in the Real World</h4><p>This may be a stretch, but I’m going to first try and explain initialisation using a real world analogy. I personally find it helps to think about abstract concepts in tangible ways in the early stages of learning. So the way I think about initialisation is the same way I think about making a cup of coffee ☕.</p><p>There’s a generally accepted blueprint for making coffee (class). A good coffee usually involves adding coffee beans, milk and sugar (properties). If we offer someone a cup of coffee (instance), we need to know how much milk and sugar they would like so that we can prepare (initialise) the coffee accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*oCxgPkhTCYqGbfFLuw69wg.png" /><figcaption>Source: <a href="https://www.homegrounds.co/maple-latte-recipe/">https://www.homegrounds.co/maple-latte-recipe/</a></figcaption></figure><p>I’ll stop there 😂 - the point I’m making is that initialisation is the act of preparing an ‘instance’ of something.</p><h4>Initialisation in the iOS World</h4><p>The Swift Programming Language Guide summarises initialisation as:</p><blockquote>“The process of preparing an instance of a class, structure, or enumeration for use.”</blockquote><p>So what does the process of ‘preparing’ an instance of a type mean? Perhaps the most important step is ensuring that all stored properties for an instance are given an initial value, whether that’s some default value or a custom value defined by the user (*<em>Optional types don’t need to be given an explicit initial value as they’re automatically initialised with a nil value</em>).</p><p>Imagine we that we want to make an instance of a class such as UIView.</p><pre>let view = UIView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: self.frame.size.width, height: self.frame.size.height)))</pre><p>A UIView is essentially a rectangular frame that has a size and location in its superview’s coordinate system. If we don’t provide a value for the frame property of a UIView instance, then the UIView can’t be properly prepared for use; a frame rectangle can’t be nil size and be in nil location!</p><ul><li>If we create an instance of a class and that class inherits from a superclass, then a key part of initialisation is setting the initial values of the superclasses stored properties.</li><li>Handling failed initialisation. For example, if someone passes the width and height parameter a value of 0 for the frame property of UIView, then we shouldn’t be creating an instance as it’s an inappropriate value for a CGRect.</li><li>There’s other things involved in ‘preparing’ an instance of a type but the above encompasses the critical things to understand.</li></ul><h3>Why do we Initialise?</h3><p>The answer is quite simple - when we create an instance of a type:</p><pre>let view = UIView() </pre><pre>//This <strong>will not</strong> result in a UIView instance fit for use.</pre><p>We initialise it so that we are confident that it’s ready for use:</p><p>The above will result in a UIView instance being created, but it will have no size or position, so it’s not very useful to us in such a state. We need to make sure that when we create an instance of a type, that we initialise it so that we are confident that it’s ready for use:</p><pre>let view = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 10))</pre><pre>//This <strong>will </strong>result in a UIView instance fit for use.</pre><p>It’s much like when we make a cup of coffee, we measure things out and stir them altogether so that the coffee is fit for consumption. If we grabbed a cracked cup, put 7kg of sugar under the cup and cold water on the coffee, then we wouldn’t really have a coffee that’s fit for consumption.</p><p>Run the following code in Xcode Playground and comment out one of the two last lines to see what I mean first hand - viewA doesn’t not appear in the assistant editor because it’s a view of an unspecified size and location.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfb38fd767cdee91a8bed45d19ac0f47/href">https://medium.com/media/bfb38fd767cdee91a8bed45d19ac0f47/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/0*elNb1FSuhFVr1zbu.jpg" /><figcaption>A ‘deconstructed coffee’. It’s not been properly initialised and is not fit for consumption.</figcaption></figure><h3>When do we initialise?</h3><p>We initialise each time we create an instance of a type. We call initialisers to create instances of types, which is something that happens a lot in object oriented programming.</p><h3>How do we initialise?</h3><h4>Setting Initial Values for Stored Properties</h4><p>We mentioned that we use initialisation to give values to all non-optional storied properties. We do this with an initialiser, which is like a method, but written using the init keyword. So instead of methodName() we have init(); an initialiser replaces the method name with the init keyword.</p><p>Suppose we have a Colour class that has 3 properties - red, green and blue:</p><pre>class Colour {<br>   var red: CGFloat<br>   var green: CGFloat<br>   var blue: CGFloat<br>}</pre><p>We can add an initialiser to perform some initialisation i.e. giving properties initial values:</p><pre>class Colour {<br>   var red: CGFloat<br>   var green: CGFloat<br>   var blue: CGFloat</pre><pre>init() {<br>   red = 1.0<br>   green = 0.5<br>   blue = 0.0<br>   }<br>}</pre><p>We create an instance of Colour by calling its initialiser:</p><pre>var newColour = Colour()</pre><pre>print(&quot;The default colour is made up of \(newColour.red) red, \(newColour.green) green and \(newColour.blue) blue.&quot;)</pre><pre>//The default colour is made up of 1.0 red, 0.5 green and 0 blue.</pre><h4>Custom Initialisation</h4><p>However, it’s unlikely that you’ll ever write code like the above! Huh? Well if you’re properties are always going to take the same initial value then it is advised that you provide the property a default value when you declare the properties in the class:</p><pre>class Colour {<br>   var red: CGFloat = 1.0<br>   var green: CGFloat = 0.5<br>   var blue: CGFloat = 0.0<br>}</pre><p>What if we want the user to be able to initialise a custom Colour? Perhaps not everyone likes orange (the colour created above). Well we can use initialisation parameters so that users can customise the initial values of the instances they create for a given type.</p><p>A parameter can have both a parameter name for use inside the initialisers body:</p><pre>class Colour {<br>   var red, green, blue: CGFloat</pre><pre>init(<strong>red</strong>: CGFloat, <strong>green</strong>: CGFloat: <strong>blue</strong>: CGFloat) {<br>   self.red = red<br>   self.green = green<br>   self.blue = blue<br>   }<br>}</pre><pre>let orange = Colour(red: 1.0, green: 0.5, blue: 0.0)</pre><p>A parameter can also have an argument label for use when calling the initialiser:</p><pre>class Colour {<br>   var red, green, blue: CGFloat<br>   var alpha: CGFloat</pre><pre>init(red: CGFloat, green: CGFloat: blue: CGFloat, <strong>withAlpha</strong> alpha: CGFloat) {<br>   self.red = red<br>   self.green = green<br>   self.blue = blue<br>   self.alpha = alpha<br>   }<br>}</pre><pre>let orange = Colour(red: 1.0, green: 0.5, blue: 0.0, withAlpha: 1.0)</pre><p>You don’t need to use argument labels. This can be avoided by putting an _ before the parameter name:</p><pre>class Colour {<br>   var red, green, blue: CGFloat<br>   var alpha: CGFloat</pre><pre>init(red: CGFloat, green: CGFloat: blue: CGFloat) {<br>   self.red = red<br>   self.green = green<br>   self.blue = blue<br>   self.alpha = alpha<br>   }</pre><pre>init(<strong>_</strong> white: CGFloat) {<br>   red = white<br>   green = white<br>   blue = white<br>   }<br>}</pre><pre>let grey = Colour(0.5)</pre><p>However, they are recommended because initialisers don’t have a name like a method or function, therefore the parameters of an initialiser play an important role in helping a user decide which initialiser should be called.</p><h4>Default Initialisers</h4><p>Swift provides a default initialiser for any type (i.e. class, struct or enumeration) that provides default values for all of it’s non-optional stored properties and doesn’t provide at least one initialiser itself:</p><pre>class Colour {<br>   var red: CGFloat = 1.0<br>   var green: CGFloat = 0.5<br>   var blue: CGFloat = 0.0<br>}</pre><pre>let colour = <strong>Colour()</strong></pre><p>The default initialiser simply creates an instance of Colour with all of its properties set with their default values. Structs receive something called a ‘memberwise’ initialiser, which serves a similar role.</p><h4>Initialiser Delegation - Value Types (Structs &amp; Enumerations)</h4><p>I want to keep this simple… initialiser delegation simply means that an initialiser can call another initialiser to perform part of an instances initialisation, which avoids duplication code across multiple initialisers:</p><p>For value types, you use self.init within an initialiser to call other initialisers for that value type. The Swift Programming Language Guide gives a great overview of initialiser delegation.</p><p>Earlier we created a UIView by passing a CGRect (i.e. a rectangle) to it’s initialiser to give the view a size and position:</p><pre>let view = UIView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: self.frame.size.width, height: self.frame.size.height)))</pre><p>That rectangle would be a type that looks a little like this:</p><pre>class CGRect {<br>   var origin = Point()<br>   var size = Size()<br>}</pre><p>The rectangle has two properties of type Size and Point, which would be types that could like this:</p><pre>struct Size {<br>   var width = 5.0, height = 5.0<br>}</pre><pre>struct Point {<br>   var x = 0.0, y = 0.0<br>}</pre><p>The CGRect instance could be initialised in one of 3 ways:</p><pre>struct Rect {<br>   var origin = Point()<br>   var size = Size()</pre><pre>init() {}</pre><pre>init(origin: Point, size: Size) {<br>   self.origin = origin<br>   self.size = size<br>   }</pre><pre>init(centre: Point, size: Size) {<br>   let originX = centre.x — (size.width / 2)<br>   let originY = centre.y — (size.height / 2)<br>   self.init(origin: Point(x: originX, y: originY), size: size)<br>   }<br>}</pre><ol><li>init() will return an instance whose origin and size properties are initialised with the default values for those types i.e. 0.0.</li><li>init(origin:size:) will allow a user to pass in a custom origin and size value.</li><li>init(centre:size:) also allows a user to pass in custom information, but specifically where they want the centre of the rectangle to be located. The initialiser then determines where the origin would be and passes the origin value to an existing initialiser i.e. init(origin:size:)</li></ol><p>The initialisers could be called as follows:</p><p>let rectOne = CGRect()</p><p>let rectTwo = CGRect(origin: Point(x: 0.0, y: 0.0), size: Size(width: 5.0, height: 5.0))</p><p>let rectThree = CGRect(origin: Centre(x: 2.5, y: 2.5), size: Size(width: 5.0, height: 5.0))</p><p>All of these rectangles initialised above would appear exactly the same i.e. with an origin of 0.0 x 0.0 and a size of 5.0 x 5.0.</p><h4>Class Inheritance &amp; Initialisation</h4><p>Initialisation for class types is slightly more complex. As mentioned, one of the key tasks of initialisation is to ensure non-optional stored properties are assigned an initial value and for classes this includes any properties that a class inherits from a superclass.</p><p>There are two types of initialiser for class types:</p><p><strong>Designated Initialisers</strong>: Initialises <strong>all</strong> properties of a class and calls the appropriate designated initialise of its superclass to continue the initialisation process up the superclass chain.</p><pre>init(parameters) {<br>   //statements<br>}</pre><p><strong>Convenience Initialisers</strong>: Are ‘supporting’ initialises for a class. They can call other convenience or designated initialisers within the same class and should ultimately call a designated initialiser.</p><pre>convenience init(parameters) {<br>   //statements<br>}</pre><p>In a complex class hierarchy the easiest way to think about things is that designated initialisers go up the class hierarchy and convenience initialisers go across:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/0*D_-nAPZAvk-PLQXj.png" /><figcaption>Source: <a href="https://docs.swift.org/swift-book/LanguageGuide/Initialization.html">https://docs.swift.org/swift-book/LanguageGuide/Initialization.html</a></figcaption></figure><p>The other important thing to understand when it comes to class initialisation is that it’s a two phase process. A ‘two-phase’ initialisation process makes initialisation ‘safe’. It prevents property values from being accessed before they are initialised and prevents property values from being set to a different value by another initialiser unexpectedly.</p><p><strong>First Phase</strong>: Is focused on ensuring each stored property is given an initial value by the class that introduced it. It then delegates up to a superclass initialiser so that it can do the same for its class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/0*-SahL0rPEzKrPb50.png" /></figure><p><strong>Second Phase</strong>: Gives each class an opportunity to customise stored properties before the new instance is considered ready for use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/0*cEzm97hk-iV3SrxQ.png" /></figure><p>OK, that’s a lot to take in. Let’s make this more tangible by looking at an example? So let’s create a base class called Drink:</p><pre>class Drink {<br>   var name: String</pre><pre>init(name: String) {<br>   self.name = name<br>   }</pre><pre>convenience init() {<br>   self.init(name: &quot;Unknown&quot;)<br>   }<br>}</pre><p>We can create a Drink instance in one of two ways:</p><p>1. We can called the Drink classes designated initialiser init(name: String) as follows let drink = Drink(“Coffee”).</p><p>2. We could also call the convenience initialiser init() as follows let drink = Drink(), which in the background will call the designated initialiser init(name: String), passing the drink parameter a string with the value “Unknown”.</p><p>Now let’s create a class called Order, which subclasses Drink:</p><pre>class Order: Drink {<br>   var quantity: Int</pre><pre>init(name: String, quantity: Int) {<br>   self.quantity = quantity<br>   super.init(name: name)<br>   }</pre><pre>override convenience init(name: String) {<br>   self.init(name: name, quantity: 1)<br>   }</pre><pre>}</pre><p>We can create an Order instance in one of three ways:</p><p>1. We can call the Order classes designated initialiser init(name: String, quantity: Int) as follows:let order = Order(name: “Coffee”, quantity: 1), which sets Order classes stored property quantity.</p><pre>init(name: String, quantity: Int) {<br>   <strong>self.quantity  = quantity</strong><br>   super.init(name: name)<br>   }</pre><p>Order classes designated initialiser then calls its superclasses designated initialiser init(name: String), passing it the name it received as a parameter argument (“Coffee”). The Drink class uses the name its passed to set the initial value of its stored property name.</p><pre>init(name: String, quantity: Int) {<br>   self.quantity  = quantity<br>   <strong>super.init(name: name)</strong><br>   }</pre><p>2. We can also create an Order instance by calling the classes convenience initialiser init(name: String) i.e. let order = Order(name: “Coffee”). The convenience initialiser calls the Order classes designated initialiser passing it the name it received as a parameter argument (“Coffee”) and a default quantity value of 1.</p><p>Anything else?</p><p>3. Well, notice how Order classes init(name: String) convenience initialiser is preceded by the override keyword? This is because it takes the same parameters as the designated initialiser from its parent class Drink. Interestingly, because the Order class has provided an implementation of all of its superclasses designated initialisers, it automatically inherits its superclasses convenience initialisers too i.e. init().</p><p>Thus we could also create an Order instance as follows:</p><p>let order = Order()</p><p>When we create an Order instance this way the inherited convenience initialiser behaves exactly the same way it does in the Drink class, except instead of calling the Drink classes init(name: String) initialiser, it calls the Order classes init(name: String) and passes it’s name parameter a string with the value “Unknown”.</p><p>OK, hold up… one more time!? What happens when we create an Order instance as follows: let order = Order()?</p><p>The Order class has inherited all of the Drink classes initialisers. Order() calls the init() initialiser that’s been inherited by the Order class from the Drink class. This initialiser then calls self.init(name: “Unknown”). Self is the Order class, so it calls Order classes init(name: String) initialiser passing it a name of “Unknown”. This initialiser then calls the Order classes init(name: String, quantity: Int) initialiser. This sets the quantity property to 1 and then calls the superclasses init(name: String) initialiser completing ‘phase 1’ of the initialisation process.</p><p>The result would be a Drink instance with drink.name of “Unknown” and a drink.quantity of 1. The best way to visualise this is to run the example code below in Xcode Playground:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/354d92bec4b49e15da0dc43c44a6d76e/href">https://medium.com/media/354d92bec4b49e15da0dc43c44a6d76e/href</a></iframe><h3>A Practical Example</h3><p>When working on apps you’ll need to give lot’s of things colours whether its text, view backgrounds, buttons when disabled etc. Suppose we want to give our view an orange background colour, it would look a little something like this:</p><pre>let view = UIView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 100, height: 100)))</pre><pre>view.backgroundColor = UIColor(red: 1.0, green: 0.5, blue: 0.0, alpha: 1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WrbvhBVWfbGEzJIGG1gnAA.png" /></figure><p>Simple? Yeah.</p><p>However, there are lots of different ways of that colours are defined. They can be defined in terms of an RGB value, RGB percent, CMY value, HSV value, Decimal, Hexadecimal… the list goes on! When we create a UIColour instance, we get given a few different initialisers in the auto suggest:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8jo5DhKOQl8XfVJa1PZBMw.png" /></figure><p>Now I quite like working with hexadecimal values because they’re quite common in the world of web development and design, so it’s what I know.</p><p>The orange colour we’ve created in our the example above is written in what’s called either RGB normalised decimal notation or RCG arithmetic notation i.e. a red, green and value value between 0 and 1. The orange colour in this notation is R: 1.0, G: 0.5, B: 0.0.</p><p>This can also be written in RGB notation as R: 255, G: 128, B: 0 or in a hexadecimal notation as #ff8000. The below should help visualise how these values all represent the same colour:</p><pre>Red = ff = 255 -&gt; 255/255 = 1.0 <br>Green = 80 = 128 -&gt; 128/255 = 0.5<br>Blue = 00 = 0 -&gt; 0/255 = 0</pre><p>I like how I only have to specify one 6 character string for a hexadecimal representation of the colour orange, it’s much cleaner than specifying 3 separate RGB values in my opinion.</p><p>Thus, I would quite like to create a UIColour as follows:</p><pre>view.backgroundColor = UIColor(fromHex: &quot;#ff8000&quot;)</pre><p>The problem is that Apple doesn’t provide a way of you initialising a UIColour from a hexadecimal. You can’t write view.backgroundColor = UIColor(hex: &quot;FF8000&quot;) as such an initialiser does not exist in the UIColour class. It’s possibly to remedy this however! The trick is to create a new convenience initialiser for the UIColour class so that we can initialiser new UIColour instances in using hexadecimal values.</p><p>The code for this is below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/813f36c8448b7c44d1d53eeec5902059/href">https://medium.com/media/813f36c8448b7c44d1d53eeec5902059/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec299c546de7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to Delegation - Swift 4]]></title>
            <link>https://medium.com/@timothydplatt/a-guide-to-delegation-swift-4-c17239dcc5f7?source=rss-296dc96c9045------2</link>
            <guid isPermaLink="false">https://medium.com/p/c17239dcc5f7</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Tim Platt]]></dc:creator>
            <pubDate>Mon, 26 Nov 2018 23:19:48 GMT</pubDate>
            <atom:updated>2018-11-28T10:16:20.504Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is delegation?</h3><h4>Delegation in the Real World</h4><p>A great place to start is by explaining delegation in the real world. In the real world delegation encapsulates someone (delegator) giving a task (delegates) to someone else (delegate). There’s two nouns and a verb that make up delegation:</p><ol><li>Delegate (verb): “To entrust a task or responsibility to another person”.</li><li>Delegator (noun): “The person who delegates to another person”.</li><li>Delegate (noun): “The person chosen or elected to represent others”.</li></ol><p>To clarify - a delegator (noun) would delegate (verb) responsibility to a delegate (noun). Now that we have the dictionary definitions of the components that make up delegation, let’s actually present a real world example of delegation:</p><blockquote>In a warehouse there will be a logistics manager (<strong>delegator</strong>), who will know when lorries are expected to arrive and when they have arrived. The logistics manager is busy and while they’re great at managing logistics, they’re not so great at unloading and moving boxes. They therefore give this job (<strong>delegate - verb</strong>) to the warehouse operatives (<strong>delegates - noun</strong>). The logistics manager tells the warehouse operatives that a lorry will be arriving at 09.00 and when it’s 09.00, they tell the warehouse operative that the lorry has arrived. The warehouse operatives then unload the lorry and moves the boxes to where they need to be.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/0*gBRrczItjBX4KwgY.gif" /></figure><h4>Delegation in the iOS World</h4><p>Delegation in the digital world is very similar to delegation in the real world, except instead of people we have have <strong><em>objects</em></strong>, which in Swift will be instances of classes, structures or enumerations. Let’s break down delegation in software development the same way we did for the real world:</p><ol><li>Delegate (verb): To entrust a task or responsibility to another object.</li><li>Delegator (noun): The class or structure instance (object) that ‘hands off’ responsibilities to an instance of another type (object).</li><li>Delegate (noun): The object that guarantees to handle the responsibilities that have been delegated i.e. provide the functionality delegated.</li></ol><p>To clarify - delegation is when one object (delegate) acts on behalf of another object (delegator) to provide functionality. Now let’s ground this down further by thinking about delegation through the perspective of participating objects:</p><blockquote>You create a to do list application. You subclass a UIViewController, to create a view controller object called ‘ToDoListViewController’ (<strong>delegate - noun</strong>). You place a UITableView instance (<strong>delegator</strong>) within the ToDoListViewController. The UITableView displays to do items and detects when it’s interacted with, but it hands off responsibility for handling those interactions (<strong>delegate - verb</strong>) to another object. The UITableView instance (<strong>delegator</strong>) will notify a delegate object of an event that it is about to handle or has just handled. The ToDoListViewController (<strong>delegate - noun</strong>) declares that it will provide the functionality to happen in response to the events handled by the UITableView.</blockquote><blockquote>Let’s suppose the UITableView instance (<strong>delegator</strong>) could talk, the object might say, “<em>I’m a table view object and row number 3 was selected</em>”. The ‘ToDoListViewController’ (<strong>delegate - noun</strong>) might say “<em>Message received, I’m going to navigate the user to the screen that corresponds to that row of the </em><em>UITableView.</em>”</blockquote><p>In the world of iOS there’s one other super important element involved in delegation - protocols. The properties and methods that will be delegated are defined in a protocol. The delegate object has to confirm to this ‘delegate protocol’ and in doing so guarantees that it will implement the functionality that it’s agreed to be a delegate for. The Swift Language Guide summarises the role of protocols as follows:</p><blockquote>Delegation is a design pattern that enables a class or structure to hand off (or delegate) some of its responsibilities to an instance of another type. <strong>This design pattern is implemented by defining a protocol that encapsulates the delegated responsibilities, such that a conforming type (known as a delegate) is guaranteed to provide the functionality that has been delegated</strong>. Delegation can be used to respond to a particular action, or to retrieve data from an external source without needing to know the underlying type of that source.</blockquote><p>Andrew Bancroft captures the moving parts well in the diagram below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/0*Ke1fql0-iT1DLgfc.png" /><figcaption>Source - <a href="https://bit.ly/2S9HKno">https://bit.ly/2S9HKno</a></figcaption></figure><h3>Why do we delegate?</h3><p>So we know a little bit more about what delegation is, but to continue to bring delegation to life we need to understand why we use delegation in the context of software development? We’ve already said that we use delegation to ‘hand off’ responsibility from one object to another, but why do we want to do that? What is the benefit of creating this separation of responsibilities?</p><p>The main benefit of an object delegating responsibility to another object is that it allows the delegating object to be versatile i.e. work in lots of different contexts but without having to have knowledge of and handle the specific contexts itself, which would otherwise result in large and tightly coupled types.</p><p>Take the UITableView as an example.</p><p>Imagine we’re building our to do list app. The to do list screen will use a UITableView. A user will be able to press a ‘+’ button to add items and swipe a cell to remove items, which will make a ‘whoosh’ sound. This screen will be managed by ToDoListViewController. The settings screen will also use a UITableView. A user will be able to see setting options and tap an option to navigate to the screen for that setting. This screen will be managed by SettingsViewController.</p><p>Now, we don’t want to extend the UITableView class to recognise when the ‘+’ button is tapped, to make a noise when a new item is added from a specific screen or to segue the user to the correct screen when a cell is tapped on the settings screen. We would end up with a colossal UITableView class that’s got lot’s of redundant functionality for many use cases.</p><p>Instead we can use delegation. The UITableView can communicate that a new row has been inserted and allow the ToDoListViewController to handle the ‘whooosh’ sound or that a row has been tapped and have the SettingsViewController decide where the user should be navigated to. The UITableView class (<strong><em>delegator - noun </em></strong>) does not need to have to know the specific logic or context of the parent UIViewController (<strong><em>delegate - noun</em></strong>).</p><p>John Sundell put’s it very well:</p><blockquote>Delegation is usually a good choice when a type needs to be usable in many different contexts, and when it has a clear <em>owner</em> in all of those contexts — just like how a UITableView is often owned by either a parent container view or its view controller.</blockquote><h3>When do we delegate?</h3><p>Delegation is described as a ‘communication design pattern’. As the name suggests we use delegation to communicate between type objects. So what kind of communication?</p><p>Firstly, delegation is used by the delegating object to communicate that an event has happened and the delegate decides how to handle that event. Secondly, sometimes delegating objects provide methods that allow the delegate object to customise something about the delegating objects properties or state.</p><p>If you read Apple’s documentation, you’ll often see that delegation methods either ‘tell’ a delegate or ‘ask’ a delegate.</p><h4>Communicate Events</h4><p>When a UITableView object is the delegator, it can communicate to a delegate object that a number of events have happened:</p><p><a href="https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614877-tableview">func tableView(UITableView, </a><a href="https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614877-tableview"><strong>didSelectRowAt</strong></a><a href="https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614877-tableview">: IndexPat</a>h - tells the delegate that the specified row is now selected.</p><p><a href="https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614963-tableview">func tableView(UITableView, </a><a href="https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614963-tableview"><strong>didEndEditingRowAt</strong></a><a href="https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614963-tableview">: IndexPath?)</a> - tells the delegate that the table view has left editing mode.</p><p><a href="https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614982-tableview">func tableView(UITableView, </a><a href="https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614982-tableview"><strong>didHighlightRowAt</strong></a><a href="https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614982-tableview">: IndexPath)</a> - tells the delegate that the specified row was highlighted.</p><p>The delegate i.e. ToDoListViewController can then decide what to do in response to this i.e. segue a user to the page corresponding to the cell selected.</p><h4>Customise Delegating Object</h4><p>When a UITableView object is the delegator, it can ask the delegate to provide information about how it should configure itself i.e. what height should it make a row or whether it should allow a row to be highlighted.</p><p><a href="https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614998-tableview">func tableView(UITableView, </a><a href="https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614998-tableview"><strong>heightForRowAt</strong></a><a href="https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614998-tableview">: IndexPath) -&gt; CGFloa</a>t - Asks the delegate for the height to use for a row in a specified location?</p><p><a href="https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614950-tableview">func tableView(UITableView, </a><a href="https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614950-tableview"><strong>shouldShowMenuForRowAt</strong></a><a href="https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614950-tableview">: IndexPath) -&gt; Bool</a> - Asks the delegate if the editing menu should be shown for a certain row?</p><p><a href="https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614988-tableview">func tableView(UITableView, </a><a href="https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614988-tableview"><strong>shouldHighlightRowAt</strong></a><a href="https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614988-tableview">: IndexPath) -&gt; Bool</a> - Asks the delegate if the specified row should be highlighted?</p><h3>How do we delegate?</h3><p>The theory is all well and good, but let’s actually put this into practice. Firstly, we will first create our own custom delegating object to show how delegation works beyond just UITableViews, which have been the main focus of this article thus far.</p><p>Secondly, we will implement a UITableView and leverage some pre-defined and commonly used delegate methods. If this doesn’t make sense just yet then don’t worry… it soon will, we just need to get our hands dirty to bring delegation more to life!</p><h4>Example 1 - Custom Delegation</h4><p>In this example ViewControllerB (delegator) recognises when a UISlider changes and if there is a delegate, it will communicate the value the UISlider changed to. ViewControllerA (delegate - noun) will nominate itself to be the delegate object. The purpose of ViewControllerA is to update the UIView that it manages to have whatever alpha the user chooses using the UISlider. It will all piece together as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*Hpv7tVMIJKt_Ix2w6We94Q.png" /></figure><p>This apps Main.storyboard is shown below, with ViewControllerA on the left and ViewControllerB on the right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*72o0i8pouyKpdDPv69Tjkg.png" /></figure><p>Before we get started, either create the above in Main.storyboard or download the <a href="https://github.com/timothydplatt/Delegation-Demo-Project">demo project from my GitHub</a> to have something to start from.</p><p>The actual app will behave as follows:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FfQrdgPMC7qPURqp3U2%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FfQrdgPMC7qPURqp3U2&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FfQrdgPMC7qPURqp3U2%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="940" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd2e8d5517858fa54bb04467994d700f/href">https://medium.com/media/bd2e8d5517858fa54bb04467994d700f/href</a></iframe><p><strong>The Delegate Protocol<br></strong>We first create the delegate protocol which will specify the responsibilities that are being delegated. In order for a delegate to conform to the protocol it must provide an implementation of all of the properties and methods defined in the delegate protocol. We will define one method updateAlpha(value: ).</p><p>The protocol may be created either at the top of the ViewControllerA file or in a standalone file. If the protocol is short and unobtrusive, I’d advise implementing it at the top of the delegator objects file i.e. ViewControllerA.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a768188303670442eca7688e9449a95/href">https://medium.com/media/8a768188303670442eca7688e9449a95/href</a></iframe><blockquote>Side Note: You limit protocol adoption to class types (and not structures or enumerations) by adding the AnyObject protocol to a protocol’s inheritance list. Since Swift 4 the preferred way to declare a class-only protocol is to use AnyObject rather than class.</blockquote><p><strong>The Delegating Object<br></strong> ViewControllerB is our delegator object. It manages the ContainerView that contains the UISlider. It has an IBOutlet and an IBAction from the UISlider.</p><p>Inside the IB action, we have two lines of code. The first line gets the value of the slider and rounds it to the nearest whole number. The second line ‘snaps’ the slider to the rounded value, otherwise the slide would sit between increments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d9c4f5ba17a1691e806a8f67513a604/href">https://medium.com/media/9d9c4f5ba17a1691e806a8f67513a604/href</a></iframe><p>We then add in two more lines of code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cc299e90b38273bb2e2868873d4cc12/href">https://medium.com/media/4cc299e90b38273bb2e2868873d4cc12/href</a></iframe><p>The first new line weak var delegate: ViewControllerBDelegate? is the way we keep a reference to the delegate object. Notice how the property is of type ViewControllerBDelegate i.e. our delegate protocol.</p><p>The second new line is delegate?.updateAlpha(value: slideValue/10), this line basically says, “if an object has declared itself a delegate, pass the value of the slide (divided by 10) to the updateAlpha(value: ) method implemented by the delegate.</p><p><strong>The Delegate<br></strong>Finally, we have ViewControllerA, our delegate object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/386a283ac9136f1390c6d52f2a8cb40e/href">https://medium.com/media/386a283ac9136f1390c6d52f2a8cb40e/href</a></iframe><p>There are two important lines chunks of code. The first effectively embeds ViewControllerB in ViewControllerA on viewDidLoad(). The most important part of the code critical to delegation is viewController.delegate = self. This code basically says, “ViewControllerB’s delegate is going to be ViewControllerA”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c87b295670bd092593a6558ca1fad66/href">https://medium.com/media/5c87b295670bd092593a6558ca1fad66/href</a></iframe><p>The other important chunk of code is below. The ViewControllerA: ViewControllerBDelegate states that the delegate view controller confirms to the delegate protocol. The code within the updateAlpha(value: Float) function is the magic… it’s the delegate providing functionality on behalf of the delegator.</p><p>The float for the value parameter was passed to the delegate when the slider was moved in ViewControllerB with this line of code: delegate?.updateAlpha(value: slideValue/10) and it’s here that this value is used to provide the functionality that we want from the updateAlpha function in this specific context. In another delegate object we may implement different functionality specific to the context of that view controller.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70ac295594eeb2a36088cc19a755c3f8/href">https://medium.com/media/70ac295594eeb2a36088cc19a755c3f8/href</a></iframe><h4>Example 2 - UITableView Delegation</h4><p><strong>The Delegating Object</strong></p><p><strong>The Delegating Protocol</strong></p><p><strong>The Delegate</strong></p><h3><strong>Recommended Reading</strong></h3><p><a href="https://www.andrewcbancroft.com/2015/04/08/how-delegation-works-a-swift-developer-guide/">How Delegation Works - A Swift Developer’s Guide</a> by Andrew Bancroft</p><p><a href="https://www.appcoda.com/swift-delegate/">Understanding Delegates and Delegation in Swift 4</a> by Andrew Jaffee</p><p><a href="https://docs.swift.org/swift-book/LanguageGuide/Protocols.html">Swift Language Guide - Protocols</a></p><p><a href="https://www.swiftbysundell.com/posts/delegation-in-swift">Delegation in Swift</a> by John Sundell</p><p><a href="https://theswiftdev.com/2018/06/27/swift-delegate-design-pattern/">Swift Delegate Design Pattern</a> by Tibor Bödecs</p><p><a href="https://medium.com/@jamesrochabrun/implementing-delegates-in-swift-step-by-step-d3211cbac3ef">Implementing Delegates in Swift</a> by James Rochabrun</p><p><a href="https://www.youtube.com/watch?v=DBWu6TnhLeY">Swift Delegate Protocol Pattern Tutorial</a> by Sean Allen</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c17239dcc5f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Taught Myself to Code - Week 7]]></title>
            <link>https://medium.com/@timothydplatt/how-i-taught-myself-to-code-week-7-e095dc5ffdba?source=rss-296dc96c9045------2</link>
            <guid isPermaLink="false">https://medium.com/p/e095dc5ffdba</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[augmented-reality]]></category>
            <dc:creator><![CDATA[Tim Platt]]></dc:creator>
            <pubDate>Mon, 19 Nov 2018 16:35:28 GMT</pubDate>
            <atom:updated>2019-03-12T08:26:04.342Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FIyL0WI3iJMM%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DIyL0WI3iJMM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FIyL0WI3iJMM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4688571fcadb10619ef197f37a7ee9e5/href">https://medium.com/media/4688571fcadb10619ef197f37a7ee9e5/href</a></iframe><h3>What did I do this week?</h3><p>I spent this week working with a friend to bring an app idea I had to life. I’m not going to give too much away as the app is still a work in progress, but it essentially involves creating an augmented reality (AR) visualisation that allows people to apply a ‘mask’ to their face (nothing too new!).</p><p>I’m going to walk through the process I went through to create a face-based AR experience instead of following my usual format of overviewing the tutorials, challenges and reading I completed. My intention is that anyone reading this blog post is able to follow along and implement their own face-based AR experience.</p><p>Here’s a quick overview of the apps current functionality:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FRejPjHQ5L0Wk4z8Xtg%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FRejPjHQ5L0Wk4z8Xtg&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FRejPjHQ5L0Wk4z8Xtg%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="940" frameborder="0" scrolling="no"><a href="https://medium.com/media/beeacfe9435a386e640b343e32fd9fb2/href">https://medium.com/media/beeacfe9435a386e640b343e32fd9fb2/href</a></iframe><h4>Prototyping the Initial Solution</h4><p>The first step was to draw a rough user experience with a pencil and paper. What different screens and components were needed? How were they linked? What was their role of each screen and component? I was then able to begin thinking about how I would create the individual screens and components that made up the solution I envisioned.</p><p>The design was quite simple. The view would show the users face as seen by the front facing iPhone camera. A custom tab bar would sit at the bottom of the screen and would display 4 options for changing the face mask. When these options were tapped, the tab bar would expand and the user is able to customise the face mask. The tab bar functionality is shown below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F1oImmagXK9Tfsq517r%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2F1oImmagXK9Tfsq517r&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F1oImmagXK9Tfsq517r%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="304" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c6234588e08f0045495a79e52a2030f/href">https://medium.com/media/0c6234588e08f0045495a79e52a2030f/href</a></iframe><p>To create the tab bar we had to implement something I’d not done before and make the main View Controller a Container View Controller. Apple sums it up pretty well:</p><blockquote>A container view controller is like any other content view controller in that it manages a root view and some content. The difference is that a container view controller gets part of its content from other view controllers. The content it gets is limited to the other view controllers’ views, which it embeds inside its own view hierarchy. The container view controller sets the size and position of any embedded views, but the original view controllers still manage the content inside those views.</blockquote><p>It’s perhaps easier to visualise by looking at the story board implementation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*GJl7Wt3M9qpbbKHk4XxJuA.png" /></figure><p>The screen on the left is managed by a Container View Controller. It contains a container view (the blue rectangle at the bottom). The container view shows content that is managed by a Child View Controller (the middle screen). The Container View Controller simply sets the position and size of that content, but has no control over what content is shown.</p><p>To make things complex, the Child View Controller (the middle screen) is also a Container View Controller. It gives up part of its view (the blue rectangle) to a child view controller (screen on the right), which is a Page View Controller. The main benefit is that it prevents huge view controllers and allows each view controller to be focused and have a primary responsibility.</p><p>The main app architecture is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EuxeoAROOEeYXIaJi97UEg.png" /></figure><h4>Creating The Face-Based AR Experience</h4><p>The next step was to create augmented reality experience. We do this by rendering a camera image (the persons face) with virtual content (a mask) into a single view, thus creating an augmented reality. Apple makes it quite simple to create basic augmented reality experiences, abstracting the developer from a lot of complex, behind the scenes maths. So let’s walk through how to create a simple AR experience.</p><p>Firstly, create a new Xcode project and select ‘single view app’. Navigate to the Main storyboard and add an ARSCN view, pin all of it’s edges to its parent view or centre it both vertically and horizontally and give it a fixed width/height.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fRohXXWRxY5iVlTkCDU9eg.png" /></figure><p>Then create an IBOutlet to the ViewController that’s created by default and name it ‘sceneView’ and write import ARKit under import UIKit, otherwise you’ll get a ‘use of undeclared type ‘ARSCNView’ error. Additionally, add import SceneKit too.</p><p>Next we need to configure and run an AR session. Create an instance of <a href="https://developer.apple.com/documentation/arkit/arfacetrackingconfiguration">ARFaceTrackingConfiguration</a>, configure its properties per Apple’s recommendations and then pass it to the <a href="https://developer.apple.com/documentation/arkit/arsession/2875735-run">run(_:options:)</a> method of the AR session associated with the <a href="https://developer.apple.com/documentation/arkit/arscnview">ARSCNView</a> that we called sceneView. The AR session manages motion tracking and camera image processing for the ARSCNView.</p><p>We also need to check that face-tracking AR is supported as it’s a capability only available on the iPhone X and later. If face-tracking AR is supported, we need to ask the user for access to their camera. Navigate to Info.plist and add a new Privacy - Camera Usage Descriptionkey. Enter the message you want to display to the user as the value for the key. So what does all that look like as code?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9961a0b3aa6601ee3bba1ef5ddd0e7f3/href">https://medium.com/media/9961a0b3aa6601ee3bba1ef5ddd0e7f3/href</a></iframe><p>If you run the code, you’ll see yourself… staring right back at you.</p><p>The next thing we need to do is add content to the persons face, it’s important to explain a few things at this point: ARFaceAnchor, ARFaceGeometry and ARSCNFaceGeometry.</p><p>When a face tracking session is running i.e. on viewDidLoad(), ARKit automatically adds <a href="https://developer.apple.com/documentation/arkit/arfaceanchor">ARFaceAnchor</a> objects to the session, containing which include information about the user’s face i.e. position, orientation, expression etc.</p><p><a href="https://developer.apple.com/documentation/arkit/arfaceanchor">ARFaceAnchor</a> contains a geometry property of type ARFaceGeometry, which is effectively a 3D representation of a persons face. It’s actually a topology of 1220 triangles stuck together to create this 3D representation, each triangle is a vertice that holds information about the persons face. The vertice at index 1064 of the ARFaceGeometry represents the persons left eye for instance.</p><p>ARSCNFaceGeometry provides a way of visually rendering the ARFaceGeometry in the sceneView. ARSCNFaceGeometry provides a way of seeing the virtual content and have it stay in the correct position as the face moves and thus the face anchor data changes.</p><p>So, basically to add virtual content to the persons face we need to make our ViewController conform to the ARSCNViewDelegate, implement the protocols <a href="https://developer.apple.com/documentation/arkit/arscnviewdelegate/2865801-renderer">renderer(_:nodeFor:)</a> delegate method and write sceneView.delegate = self in our viewDidLoad().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66738d2b9aa379caca4f9e8edd01f99c/href">https://medium.com/media/66738d2b9aa379caca4f9e8edd01f99c/href</a></iframe><p>The result is that the image named ‘maskImage’ is now applied to the persons face and rendered in the ARSCN view.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F328sqiud1oywTGJEhD%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2F328sqiud1oywTGJEhD&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F328sqiud1oywTGJEhD%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="940" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc4f77aebe5790275731e702f5801ff5/href">https://medium.com/media/dc4f77aebe5790275731e702f5801ff5/href</a></iframe><p>You’ll notice however that the mask doesn’t move with the persons face such as when they blink or open their mouth. This is because the when the ARSCNFaceGeometry changes our ARSCNView is not being informed or doing anything with the new ARSCNFaceGeometry data. To address this we implement another ARSCNViewDelegate protocol method called renderer(_:didUpdate:for:):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b5df059d1407c18594f8b93a77a90a1/href">https://medium.com/media/0b5df059d1407c18594f8b93a77a90a1/href</a></iframe><p>The result should now be something like below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F1wX9CEqdS2Oj9JUjQq%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2F1wX9CEqdS2Oj9JUjQq&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F1wX9CEqdS2Oj9JUjQq%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="940" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2870c267b36b44a552162d63f16829c/href">https://medium.com/media/c2870c267b36b44a552162d63f16829c/href</a></iframe><p>You can change the maskImage to apply a new ‘mask’ to a persons face and have it track their face position, expressions and movement. There’s more that you can do i.e. handling facial expressions, add 3D content (think glasses that hook over your ears) etc but that’s beyond the scope of my MVP.</p><h4>Editing the Face Mask</h4><p>Another large piece of functionality that we had to figure out was handling the changes to the ‘mask’ i.e. if the user wanted to adjust the transparency, colour, position or even type of mask, how could that be done? My friend told me it was possible to modify, merge and create new images. He suggested that I split the mask into multiple images, applying changes to the appropriate image and then merge the multiple images into a single ‘mask’. So let’s look at how I went about this:</p><p><strong>Change the Transparency of Mask<br></strong>This wasn’t as simple as I thought it would be. The issue was that it’s easy to change a UIImageView i.e. the view that holds an image, but not the UIImage i.e. the actual image itself. I had to extend UIImage and create a new function that took an alpha value (between 0 - 1) and returned my image with the appropriate alpha applied.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81627882c9a67f1f73050d8dcb2d3fa4/href">https://medium.com/media/81627882c9a67f1f73050d8dcb2d3fa4/href</a></iframe><p>I then used this function as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1f20a090420fd362a13a696094e4aa7/href">https://medium.com/media/e1f20a090420fd362a13a696094e4aa7/href</a></iframe><p>Another issue I had, was that if I tried to change the masks transparency multiple times i.e. to 0.9 and then to 0.5, it would work correctly the first time but the second time it would give effectively me an alpha of 0.45 as the original image now had an alpha of 0.9. I had to get around this with some head banging/creative coding.</p><p><strong>Change the Colour of Mask<br></strong>I had to extend UIImage again (I got the code from StackOverflow) and I don’t fully understand how it works but it effectively changes the colour of a single colour image to a different colour:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b210907fd620b1c3bbdf89a782a792b2/href">https://medium.com/media/b210907fd620b1c3bbdf89a782a792b2/href</a></iframe><p>I then used the function like follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3321fb71eb489d9704e075e19ec23d8/href">https://medium.com/media/b3321fb71eb489d9704e075e19ec23d8/href</a></iframe><p><strong>Change the Position of Mask<br></strong>To combine two images I used UIGraphicsBeginImageContext() to create an image of a specific size. I then drew my two existing images within that image ‘context’, but I drew them at an offset, which clipped the images giving the appearance they’d moved position.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbb6e6f0a697cb055919e9d928fb27f9/href">https://medium.com/media/dbb6e6f0a697cb055919e9d928fb27f9/href</a></iframe><h3>What were the highlights?</h3><ol><li><strong>Creating a Working App</strong>.<strong> </strong>I literally had no idea where to begin or if it was even possible ~2 weeks ago, but after hours of Googling, experimentation and frustration… I arrived at a loose idea as to how I could make my idea a reality. A few days later I had a fully function, albeit far from perfect, mobile app.</li><li><strong>Learning from a Friend</strong>.<strong> </strong>It’s been super valuable partnering with a friend at key junctions in the development of this app. My friend is an experienced iOS developer and it was great to watch him think about the problem at hand and then decipher what the right tool for the job was. For instance, when it came to creating the custom tab bar I had no idea where to start but my friend immediately has 3 possible solutions in mind. This will come with time as some of those solutions were using views I’d never used before!</li><li><strong>Swift Lint</strong>. Swift Lint is basically a tool that highlights coding bad practice in your source code, so things like too many characters on one line or too many variables included in a tuple. It takes some configuring (there’s so much poor documentation in software engineering!) but it’s genuinely improved the readability of my code and educated me on what best practice looks like.</li></ol><h3>What were the biggest challenges?</h3><ol><li><strong>Git Hub Knowledge</strong>.<strong> </strong>I quickly realised I hadn’t got a clue what I was doing when it came to version control and it really is a deal breaker when it comes to working on a shared code base. It really does pay off taking the time to learn how GitHub works. I ended up creating a new working copy of my Xcode project each day and keeping it all stored on my Macbook Pro, which is really bad practice.</li><li><strong>Knowing Where to Begin</strong>.<strong> </strong>One of the hardest things about coding is knowing where to begin. I found myself wondering which types of view should I use to create the user experience? How am I going to apply a mask to a persons face, which follows their expression/movements? How do I give the person the ability to change the position, colour, transparency of the mask? I think this gets easier as you gain more experience… I also think that grabbing a pencil and paper and sketching out possible solutions really helps me as it makes the problem tangible. Finally, I think there’s a lot of truth to something another friend once said, which is that “90% of writing code is knowing how to type the right thing into Google”.</li><li><strong>Not Reading the Instructions</strong>. I have quite a poor attention span and I often skim read the instructions but don’t actually digest them meaningfully. On one occasion I spent hours trying to understand how I changed the mask that’s placed on the persons face and it literally required adding 3 lines of code to the renderer(_:didUpdate:for:) protocol method, but I didn’t understand the method fully to realise this. It’s well worth printing output from within methods to understand when they’re triggered and what information they’re taking/outputting. The renderer(_:didUpdate:for:) method for instance triggers 100’s of times a second (each time the users face changes i.e. they raise their eyebrows) and I had no idea (try print #function - a nifty little trick my friend taught me).</li></ol><h3>Summary</h3><p>It’s been super rewarding making something that I initially thought would be well beyond my capacity. I’ve realised that I’ve both come a long way (sometimes I can’t believe the conversation’s I’m having with professional engineers) but I also have a long way to go (there’s a lot of basics I still don’t understand). However, a key mindset to being able to learn to code is having self-belief in your ability to solve problems or capacity to acquire the skills needed to solve problems.</p><p>A lot of people, including me, say things like, “I’m crap at maths” or “this is beyond me”… but that’s only true if you give up there and then… to not be crap and to not have things be beyond you means persevering and believing in your ability to master the things you don’t currently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oJZt2DhqCrwDqUhvZXPWcA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e095dc5ffdba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Being Agile vs. Doing Agile - Part 1]]></title>
            <link>https://medium.com/@timothydplatt/being-agile-vs-doing-agile-part-1-de9589bca1a1?source=rss-296dc96c9045------2</link>
            <guid isPermaLink="false">https://medium.com/p/de9589bca1a1</guid>
            <category><![CDATA[work]]></category>
            <category><![CDATA[scrum]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[organizational-culture]]></category>
            <dc:creator><![CDATA[Tim Platt]]></dc:creator>
            <pubDate>Wed, 19 Sep 2018 08:42:21 GMT</pubDate>
            <atom:updated>2018-09-19T08:42:21.150Z</atom:updated>
            <content:encoded><![CDATA[<h3>An Introduction</h3><p>To <strong><em>do</em></strong> agile is not the same thing as to <strong><em>be</em></strong> agile. This two-part article intends to illustrate the difference between <strong><em>doing</em></strong> agile and <strong><em>being</em></strong> agile in relation to each of the 12 principles behind the agile manifesto. It does so with good intentions and using relatable examples; hoping to help others understand how they can increase their agility and reap the rewards that go with it.</p><h3>Differentiating Between ‘Doing’ &amp; ‘Being’</h3><p>Doing agile is focusing on implementing specific <strong><em>frameworks</em></strong>, <strong><em>processes</em></strong> and <strong><em>tools. </em></strong>The focus is on doing the above (i.e. box-ticking) vs. doing the above meaningfully and mindfully. It’s relatively easy to <strong><em>do</em></strong> agile:</p><ul><li>You adopt a team level <strong><em>framework</em></strong> like scrum or kanban.</li><li>Larger organisations will probably also adopt a <strong><em>framework</em></strong> for scaling agile such as SAFe, LeSS, ‘The Spotify Model’ or <a href="http://www.agilescaling.org/ask-matrix.html">similar</a>.</li><li>You implement new <strong><em>processes</em></strong> and ceremonies i.e. sprint planning, backlog refinement, retrospectives, daily stand-ups or a variation of these.</li><li>You try new <strong><em>practices</em></strong> i.e. writing product backlog items (PBI’s), working iteratively etc and support these with new <strong><em>tools</em></strong> i.e. Jira, Rally etc.</li></ul><p>Doing agile is only of value if it helps an organisation to achieve a state of being agile. It’s likely that you’re seeing <em>incremental gains</em> as a result of doing agile; after all it’s a sensible way to approach delivery.</p><p><strong><em>Being</em></strong> agile, on the other hand, is about much more than implementing and adhering to frameworks, processes and tools. The first agile value is <em>“individuals and interactions over processes and tools”. </em>The agile manifesto states that while there is value in the items on the right i.e. processes &amp; tools, that we should value the items on the left more i.e. the individuals and interactions; or more simply put the <strong><em>people</em></strong>. So while there’s value in implementing frameworks and processes, the thing that delivers <em>transformation gains</em> is the behaviours and mindsets of the people that operate within them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eM-JRVHM0vVN6o0f.jpg" /><figcaption>Frameworks, processes &amp; tools are just the tip of what’s needed to achieve agility.</figcaption></figure><p>In essence, to be more agile, we need to focus on fostering agile mindsets by concentrating on the values, attitudes and behaviours of the <strong><em>people</em></strong> that make up the organisation and the setup and culture of the <strong><em>organisation</em></strong> itself.</p><blockquote>“When organisations are <em>doing agile</em>, they are asking, “What do I need to do Agile and how?”– implying they are ruled by framework, methodology, tools and techniques. Whereas when they are <em>being Agile</em>, they are asking, “Why do I need to be Agile and how?” This implies that they are more concerned with the kind of behaviour, mindset and thinking necessary to succeed.” - <a href="https://blogs.dxc.technology/2018/05/06/the-agile-maturity-pyramid-whats-the-difference-between-doing-agile-and-being-agile/">Mazdak Abtin</a></blockquote><p>Fostering agile mindsets requires changes to the way <em>people</em> are managed, rewarded, trained, motivated and hired. Individuals are entrusted with responsibility and managers become enablers vs. task masters. Organisations reward people for demonstrating agile behaviours/agility i.e. championing face to face collaboration, shortening feedback loops in the delivery process and making decisions that sustain and support long-term agility. People are motivated to achieve a vision and they’re empowered to take ownership of the goals that will move the organisation towards that vision, which gives them and their work meaning and purpose.</p><p>Being agile will also mean re-configuring some of the ways your organisation is setup and adjusting the organisational culture. An organisation may need to amalgamate functions to reduce handovers, increase collaboration and ensure all the skills required to own a solution exist within a team. There may be a need to collapse hierarchies to decentralise responsibility and catalyse self-organisation. Organisations will need to create an environment where leadership embrace the values and guiding principles of agile and not circumvent those values when it’s convenient to do so. Organisation will need to re-think job families and career progression paths within them.</p><p>The most elegant embodiment of what I’ve tried to detail above is exemplified in the below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L_pVT8X9L-nsH3owB5U5tA.jpeg" /><figcaption><a href="https://blogs.dxc.technology/2018/05/06/the-agile-maturity-pyramid-whats-the-difference-between-doing-agile-and-being-agile/">The Agile Maturity Pyramid</a></figcaption></figure><h3>Illustrating Being Doing vs. Being Agile</h3><h4>Principle 1 - Our highest priority is to satisfy the customer through early and continuous delivery of valuable software.</h4><p>Firstly, let’s focus in on the ‘<em>our highest priority is to satisfy the customer</em>’ part of this principle (n.b. how it’s <strong><em>customer</em></strong>, not <em>user</em>!). An organisation that <strong><em>does</em></strong> agile may analyse some data, infer a customer need and then create product backlog items using the ‘<em>as a customer, I want, so that</em>’ prose. They will then deliver those product backlog items into market and a mature agile team will validate that it satisfies the needs of their user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*jYpbRZAuAQUhlTSk.jpeg" /><figcaption>Engaging Customers Early &amp; Often = Shorter Feedback Loops &amp; Valuable Products</figcaption></figure><p>How does this differ from an organisation that <strong><em>is</em></strong> agile? An indicator of agility is the ability to directly engage with and involve your customers in the delivery process itself. Instead of just analysing customers as if they were black boxes, we instead form a dialogue with them to build empathy and understand the emotional drivers behind their needs. In doing so, what it means to ‘<strong><em>satisfy</em></strong><em> the customer</em>’ and ‘<em>deliver </em><strong><em>valuable</em></strong><em> software</em>’ becomes less subjective. These interactions take place early and often throughout delivery and they help teams elicit feedback that will maximise the value of the product they deliver.</p><p>If the time it takes to ship a product increment to market is less than the time it takes to remove the red tape between an agile team and a customer interaction, then you have an opportunity to improve your agility.</p><figure><img alt="Image result for guerilla testing" src="https://cdn-images-1.medium.com/proxy/1*ttmN9oTYlPWTgBsgtt49qQ.png" /><figcaption>Guerilla Testing With Prototypes Can Be Comedic!</figcaption></figure><h4>Principle 2 - Welcome changing requirements, even late in development. Agile processes harness change for the customer’s competitive advantage.</h4><p>I want to clarify that to be agile does not mean changing lot’s of thing lot’s of the time; after all, change is often time consuming and creates re-work. Experiencing change frequently is often symptomatic of other problems i.e. poor backlog refinement, unaligned product priorities, bringing work into sprints pre-maturely etc. However, it’s how teams respond to change (their mindset) that differentiates between those that <em>do</em> and those that <em>are</em> agile.</p><p>Agility looks like this. A team member who understands the user need behind the work that they’re doing recognises the need to make a change late in an iteration. They socialise this with their team without fear of hearing a collective, “Oh, for fuck sake!”. The team is pragmatic and understand that things change as new information emerges. They agree it’s in the customers best interest that the change is made before releasing the current increment. On other occasions they may choose to address the change at a later date.</p><p>The impact to other priorities is minimal because the team bakes capacity into their estimates and sprints for this kind of unknown. If the team doesn’t have the capacity, they de-prioritise lower priority work to make the change. The team and stakeholders understand that sometimes making changes, even late on, is for the greater good.</p><h4>Principle 3 - Deliver working software frequently, from a couple of weeks to a couple of months, with a preference to the shorter timescale.</h4><p>If you’re <strong><em>doing</em></strong> agile one of the biggest benefits you’re seeing over the old ways of working is that you’re quicker to produce working software and you’re producing new increments of working software every sprint. It’s software that has been unit tested, de-bugged, integrated into the pipeline and is <em>theoretically</em> shippable. This is a step in the right direction; remember when we used to perform integration, regression and user acceptance testing towards the end of the delivery cycle? However, if you’re simply taking what would previously be a 6 month project and breaking it into 2 week sprints, you’re falling a little short.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F4VWrs87jljRq9I6fRq%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2F4VWrs87jljRq9I6fRq&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F4VWrs87jljRq9I6fRq%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="192" frameborder="0" scrolling="no"><a href="https://medium.com/media/be4039a9e9652327357cf29119ba865c/href">https://medium.com/media/be4039a9e9652327357cf29119ba865c/href</a></iframe><p>Agility <strong><em>is</em></strong> not only shipping working software frequently, but shipping software that’s ‘<em>working</em>’ from the perspective that it’s either providing utility to the customer or a validated learning opportunity for the agile team (not just tested, de-bugged, deployed etc). You’re <strong><em>agile</em></strong> when as an organisation you’re comfortable shipping working software is not the fully polished end article but you know it will provide some utility/learning and in turn result in a better end product.</p><h4>Principle 4 - Business people and developers must work together daily throughout the project.</h4><p>Co-location would be the easy target for this principle, but I appreciate that it’s not always practical to co-locate a substantial amount of your workforce. Let’s instead examine two hypothetical organisations that that we’ll assume have all of their employees co-located.</p><p>The first organisation has a pizza sized scrum team that sits together and follows typical agile ceremonies that work for them. The teams product manager (PM) works in a different department, under different leadership and attends the odd sprint planning. The teams designer sits within an internal agency of sorts, which has their own priorities separate to that of the product teams; the designer attends refinement ceremonies only when working on one of the scrum teams features. From the PM’s perspective, working together isn’t much more than giving the team finished designs to build, asking them for updates as to when it will be done and accepting user stories. The scrum team does some invisible work to improve the platform because it’s not the concern of the PM.</p><p>The second organisation has a pizza sized scrum team that includes a product manager, designer and generally the people required to be able to own a solution end to end with minimal dependency on others. They are aligned behind common goals and have the same set of transparent priorities. They co-create solution as a team in face to face sessions. Through their close collaboration they impart new skills and domain knowledge on their fellow team members, further reducing their dependencies. The team finds it easy to have organic and impromptu ‘jams’ to tweak and change solutions as new insights emerge or needs change. The individuals within the team will actively engage in their respective communities of practices, bringing learnings and shared best practices back to their respective scrum teams.</p><p>Unless organisations evolve their structures the ‘working together’ picture painted by the second team may seem will remain a distant nirvana.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2d_j5JXuHZRksMJXNulaAg.jpeg" /><figcaption>Build ‘<a href="https://www.agil8.com/component-teams-vs-feature-teams/">Feature Teams’</a> That Can Own Solutions End to End</figcaption></figure><h4>Principle 5 - Build projects around motivated individuals. Give them the environment and support they need, and trust them to get the job done.</h4><p>This principle places emphasis on people. I’ve already stated that while there’s value in implementing frameworks and processes, being agile is about much more. It’s the behaviours and mindsets of the people that operate within the frameworks and processes that’s key to achieving agility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*y-LRB0YdnCGZUXNGN66JYg.png" /><figcaption><a href="https://www.slideshare.net/krlooney/austin-product-camp-11-agile-doing-vs-being">Being vs. Doing Agile</a></figcaption></figure><p>The way organisations motivate people is an interesting indicator of agile maturity.</p><p>An organisation that leans more towards <em>doing</em> agile primarily uses extrinsic motivators i.e. external rewards and reinforcers. Rewards may include bonuses, promotion or praise and will often correlate heavily to the amount of work delivered and in more mature organisations to the quality of the work deliver and the behaviours demonstrated. Reinforces include policy and procedure or disciplinary action, which motivate people to work within a control… often within the ‘old way of working’</p><p>Organisations that lean more towards <em>being</em> agile will use extrinsic motivators but are equally as concerned with fostering intrinsic motivations. Intrinsic motivation involves engaging in a behaviour because it is personally rewarding, it’s behaviour that arises from within. Some examples of internal rewards are enjoyment, achievement, a sense of competence. An example of an internal reinforcer is a guilty conscience.</p><p>A simple means of cultivating intrinsic motivation is by having a clear vision. A vision is an articulation of your organisation or products overarching aspiration; it’s purpose.</p><p>IKEA just simply sell affordable, flat pack furniture:</p><blockquote>“At Ikea, our vision is to create a better everyday life for the many people.”</blockquote><p>Innocent smoothies don’t just sell tasty fruit juice, they instead:</p><blockquote><em>“Make natural, delicious food and drink that helps people live well and die old”</em></blockquote><p>A strong vision will give people a sense of purpose and thus intrinsic motivation. Build projects and roadmaps around motivated people that model intrinsic behaviour. Cultivate intrinsic behaviours by giving people purpose. After all, everything an organisation does, it does through people.</p><h4>Principle 6 — The most efficient and effective method of conveying information to and within a development team is face-to-face conversation.</h4><p>What are some indicators of biasing towards <strong><em>being</em></strong> vs. <strong><em>doing</em></strong>?</p><p>Agility is not having to go through <em>proxy people</em> when it’s not convenient for anybody. If you’re a developer and you want a quick conversation with legal to check some 3rd party licensing query then organisational structures and culture should allow that conversation to happen.</p><p>Agility is when teams use tools like Slack for instance, to support face to face collaboration vs. replace collaboration. “It’s on Slack” should not be the totality of a teams communication.</p><p>It’s not only having regular, scheduled face to face conversations but organic and sometimes spontaneous face to face co-creation. Where a designer can ask a developer and product manager to pull up a chair to sketch out some possible improvements to a gap they’ve just identified in the current solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*T66Y0Xw4f0trRLfU.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de9589bca1a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Taught Myself to Code - Week 6]]></title>
            <link>https://medium.com/@timothydplatt/how-i-taught-myself-to-code-week-6-36a4f14f135?source=rss-296dc96c9045------2</link>
            <guid isPermaLink="false">https://medium.com/p/36a4f14f135</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[product-management]]></category>
            <dc:creator><![CDATA[Tim Platt]]></dc:creator>
            <pubDate>Sun, 09 Sep 2018 22:57:06 GMT</pubDate>
            <atom:updated>2018-09-10T07:19:26.075Z</atom:updated>
            <content:encoded><![CDATA[<h3>What did I do this week?</h3><p>I would summarise this week by saying that I went back to some Swift ‘<em>basics’</em>. I took a whistle stop tour through control flows, functions, optionals, classes, structures, enums, properties, initialisation and collections. I also got hands on with scroll views; a Swift ‘<em>basic</em>’ that I hadn’t touched prior to this week.</p><p>So, why back to basics? Firstly, I’m still a beginner and as my understanding of Swift evolves, it affords me to go back and further understand aspects of the basics that I didn’t grasp previously (or nuances/details I missed first time around). Secondly, there’s a lot I’ve skipped as I’ve jumped to more fancy stuff (i.e. using CoreML) and I therefore have knowledge gaps that I need to plug.</p><h4>Tutorials</h4><p>I started the week by signing up for a paid subscription to <a href="https://store.raywenderlich.com/products/subscription">Ray Wenderlich</a> as I’ve completed all of the <a href="https://www.udemy.com/ios-11-app-development-bootcamp/learn/v4/content">Angela Yu’s tutorials</a> that I’m currently able to. Plus, I appreciate how important quality resources are to my progression and Ray Wenderlich’s website is one of the most reputed.</p><p><a href="https://www.raywenderlich.com/5994-programming-in-swift"><strong>Programming in Swift</strong></a><strong><br></strong>I spent the first couple of days completing <a href="https://www.raywenderlich.com/5994-programming-in-swift">Programming in Swift</a> by Jessy and Catie Catterwaul. I learned a couple of nifty things, for example if you create a custom type in Swift you can give it a description that appears when someone option + clicks the type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1303349a12abcdd7ae2906a6dc74481/href">https://medium.com/media/c1303349a12abcdd7ae2906a6dc74481/href</a></iframe><p>This will then appear as follows when you option + click Person. I liked this as it helps others to understand your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2267cbWCz-oCGnLiX2T9w.png" /><figcaption>Using `///` to create a custom type description.</figcaption></figure><p>I also learned about type aliases, which allow you to define an alternative name or synonym for an existing type i.e. you could use Volume instead of Int when you want to refer to a type by a name that’s more contextually appropriate. I like the idea of using them to make closures easier to read. For example, say we have a function that takes a closure as a parameter:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/474a85f0fdddfd8db47023101e35b880/href">https://medium.com/media/474a85f0fdddfd8db47023101e35b880/href</a></iframe><p>We can create a type alias for that closure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff48d8ab6c4db7ac5bf5eb410bd0a9e1/href">https://medium.com/media/ff48d8ab6c4db7ac5bf5eb410bd0a9e1/href</a></iframe><p>We can then write the function above in a way that’s less verbose:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d4a0e994ac78e996b88e34b213c3202/href">https://medium.com/media/2d4a0e994ac78e996b88e34b213c3202/href</a></iframe><p>The above defines the type onCompletion to be the same as (Int, Int) -&gt; Int. You could use the two interchangeably in your code moving forward. To clarify one more thing (as I didn’t understand the below):</p><p>var onCompletion = (Int, Int) -&gt; Int is incorrect and will not compile. You can’t assign a type to a variable or constant.</p><p>var onCompletion: (Int, Int) -&gt; Int is fine. You can declare a variable that has type: (Int, Int) -&gt; Int.</p><p>There were two other <strong><em>stand out</em></strong> things that I learned about. The first was for in loops. Now, for in loops are one of the first control flows you learn about in programming but I’d not really covered them in Swift before (I assumed their syntax was identical to for loops in Java). If you don’t know about loops in Swift, then it’s a must learn as they’re used everywhere…Swift is a lot of for in loops, collection types and closures! So a few for in loop examples:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16bfb2e6b8eda4ef3a0f2f01d4d22dd8/href">https://medium.com/media/16bfb2e6b8eda4ef3a0f2f01d4d22dd8/href</a></iframe><p>I actually much prefer Java’s way of doing for loops for(int i = 0; i &lt; 10: i++) but perhaps my general preference of Java’s more verbose syntax will disappear over time!?</p><p>The second <strong><em>stand out</em></strong> topic I covered was collections. In Swift there are 3 main collections ‘out of the box’, these are arrays, sets and dictionaries (Java has a lot more). I should stress at this point that all tutors emphasise the importance of learning about collections and I’ve found that you pretty much use collection types everywhere so do invest the time! A collection type is essentially a container for values and each collection type has it’s own traits/benefits over another making them more suited to a particular task at hand.</p><p>The most interesting learning for me was how closures (see <a href="https://medium.com/@timplatt/how-i-taught-myself-to-code-week-5-caf6fee6d825">previous blog post</a>) and collections can be use together in really powerful ways. For example, we can sort an array collection type using the sort(by: ) method, which iterates over an array and sorts the elements using a predicate that you pass in as a closure. The method takes a closure parameter and the closure parameter in the below is of type (String, String) -&gt; Bool:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0c4c6c66adc330ed64c77b0c40781bd/href">https://medium.com/media/b0c4c6c66adc330ed64c77b0c40781bd/href</a></iframe><p>Interestingly, the closure type matches the type of the array that you use sort(by: ) method on. So if you sort an array of Integers, the closure would be of type (Int, Int) -&gt; Bool. Awesome!</p><p>Using methods that take closures as arguments on collection types is often a cleaner alternative to using for in loops. So for example if we have a dictionary of people and their age, and we wanted to create a new dictionary of people older than 18, we could use a for in loop:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b668e574faf9328834586731b014356/href">https://medium.com/media/5b668e574faf9328834586731b014356/href</a></iframe><p>Now we could do this using the filter method and passing it a closure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5b196a6581e72b4ccfc7438a7991869/href">https://medium.com/media/f5b196a6581e72b4ccfc7438a7991869/href</a></iframe><p>You can even chain methods. The example below sorts a dictionary in order of it’s keys, then it filters the dictionary to only include key:value pairs of people who are older than 18:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d99caab172f55b9f5ad247ef5b9e26ae/href">https://medium.com/media/d99caab172f55b9f5ad247ef5b9e26ae/href</a></iframe><p>There’s a few methods worth getting familiar with when it comes to collections: filter, map, reduce, flatMap, compactMap and quite a lot of good material on the subject such as <a href="https://codeburst.io/swift-map-flatmap-filter-and-reduce-53959ebeb6aa">Santosh Botre’s</a> or <a href="https://medium.com/@abhimuralidharan/higher-order-functions-in-swift-filter-map-reduce-flatmap-1837646a63e8">Abhimuralidharan’s</a> articles.</p><p><a href="https://www.raywenderlich.com/5298-reproducing-popular-ios-controls"><strong>Reproducing Popular iOS Controls</strong></a><strong><br></strong>On Wednesday I started following the <a href="https://www.raywenderlich.com/5298-reproducing-popular-ios-controls">Reproducing Popular iOS Controls</a> tutorials but I quickly found myself out of my depth. The project used complex storyboard layouts and scrollviews, the former I’ve not touched in that degree of detail before and the latter I haven’t touched at all. I did follow along and produced the animation below, but I can’t say I understood it (yet).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F9_smBluljm8%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D9_smBluljm8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9_smBluljm8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/656aa5067043bb8545f26843e3fe0d3b/href">https://medium.com/media/656aa5067043bb8545f26843e3fe0d3b/href</a></iframe><p><a href="https://www.raywenderlich.com/4040-scroll-view-school"><strong>Scroll View School</strong></a><br>So, I thought well why not educate myself on autoLayout and scrollviews and come back stronger? So I completed the <a href="https://www.raywenderlich.com/4538-beginning-auto-layout">Beginning Auto Layout</a> tutorial (awesome) and <a href="https://www.raywenderlich.com/4040-scroll-view-school">Scroll View School</a>. The former was super useful as I’d only scratched the surface in Angela Yu’s tutorial’s. The scrollview tutorial, well that I’m still wrapping my head around.</p><p>Firstly, I made my first scrollview (and also used gesture recognisers for the first time which involved weird #selector syntax which made zero sense):</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FQ160XhLbJSo%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DQ160XhLbJSo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FQ160XhLbJSo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b96d9ce094413ffa24833fff57abaf1e/href">https://medium.com/media/b96d9ce094413ffa24833fff57abaf1e/href</a></iframe><p>Then I made a single page app to apparently help visualise frames vs. bounds (bounds I find tricky to wrap my head around). Doing well huh!?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fqa1MWQ4Y-B8&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dqa1MWQ4Y-B8&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2Fqa1MWQ4Y-B8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4619029cb4d57ca1471cf3f549a083d/href">https://medium.com/media/b4619029cb4d57ca1471cf3f549a083d/href</a></iframe><p><a href="https://medium.com/@anitaa_1990/create-a-horizontal-paging-uiscrollview-with-uipagecontrol-swift-4-xcode-9-a3dddc845e92"><strong>Horizontal Paging UIScrollView Tutorial</strong></a><strong><br></strong>Then, I decided I wanted to learn how to make an ‘on-boarding’ journey that are common on many apps (I assumed they used a horizontal scrollview). I’ve always found If This Then That’s on-boarding mesmerising:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fsz5bu_KVNJQ%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dsz5bu_KVNJQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fsz5bu_KVNJQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8869630f192190a2e95a978e71ee9ad3/href">https://medium.com/media/8869630f192190a2e95a978e71ee9ad3/href</a></iframe><p>That’s where I found this <a href="https://medium.com/@anitaa_1990/create-a-horizontal-paging-uiscrollview-with-uipagecontrol-swift-4-xcode-9-a3dddc845e92">awesome tutorial by Anitaa Murthy</a>. At first I didn’t understand the code, but then I spent the day dissecting it…printing variables to the console, change variable to see what happen when I ran the app, option + clicking different methods and properties. After a number of hours I fully understood the code; my persistence paid off.</p><p>I was even able to modify the code to add rotate the image relative to the amount the scrollview was moved by the user (the original project only scaled the image relative to the amount the scrollview was moved). I had to concatenate two transforms together to have the image both rotate and scale concurrently. The result was as follows:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FAMyUYfYvgrk%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DAMyUYfYvgrk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FAMyUYfYvgrk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/065fe72d8f00e882971f3cc992e8ce70/href">https://medium.com/media/065fe72d8f00e882971f3cc992e8ce70/href</a></iframe><p>A few key callouts/learnings from the ‘on-boarding’ journey above. Firstly, scrollView.isPagingEnabled = true is an amazing bit of code that makes the scroll view stop on multiples of the scroll view’s bounds when the user scrolls. In simple terms, it breaks the content up into screen sized chunks, to create a paging effect.</p><p>Another callout. When using scrollviews, you can implement the method scrollViewDidScroll which is called each time the scrollview is moved. You can find out how much the scroll view was moved both vertically and horizontally by using scrollView.contentOffset.x and scrollView.contentOffset.y. In the code below, we use the content offset to set the page index of the page control:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09d8fe56e094f1c048a9708121cb3c7f/href">https://medium.com/media/09d8fe56e094f1c048a9708121cb3c7f/href</a></iframe><p>The code is basically saying… if the scroll view has moved by more than half the width of the screen, we’ve moved to the next page, otherwise we’re still on the current page.</p><p>Finally, to create the image scaling and rotation in the video we usedCGAffineTransform functions to create transformations with very little code. Transforms allow you to scale, rotate or move objects and views.</p><pre>let translate = CGAffineTransform(translationX: 100, y: 100)<br>let rotate = CGAffineTransform(rotationAngle: 180)<br>let scale = CGAffineTransform(scaleX: 10, y: 10)</pre><p>I spent 30 minutes reading <a href="https://medium.com/@figueroa_xio?source=post_header_lockup">Xiomara Figueroa</a>’s blog on <a href="https://medium.com/written-code/ui-animations-with-swift-2ebb5e6d2292">UI Animations in Swift</a> and went from knowing nothing about iOS animations (and thinking they were probably impossibly difficult) to being able to create animations in relation to the movement of a scroll view. Epic! The code looks scary:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34bd6bae0497bf9e05b58f2f0c3d8fc9/href">https://medium.com/media/34bd6bae0497bf9e05b58f2f0c3d8fc9/href</a></iframe><p>What it’s basically saying is… when scrolling between page the first and second pages, transform the images ‘<em>scale</em>’ relative to the amount that’s been scrolled. Then we concatenate another transform and ‘<em>rotate</em>’ the image relative to the amount that’s been scrolled.</p><p>Please don’t get stressed out by this code. It took me hours of tinkering to understand it. I still don’t actually fully understand the formula I wrote for the rotation 😂.</p><h4>Reading</h4><p>I read about two topics: properties and initialisation. I’ve previously glossed over these ‘basics’ in an attempt to maximise my time learning as much as possible. I assumed there wasn’t much more to these topics and what I learned from <a href="https://courses.caveofprogramming.com/p/java-for-complete-beginners">Java For Complete Beginners</a> would allow me to get by, which it did.</p><p>However, as I tinker with more code I find myself seeing lot’s of syntax that I don’t quite understand; thus it felt like a good time to devote some energy to understanding properties and initialisation. BTW, I still don’t fully understand either topic, but I know a whole lot more and enough to be dangerous (in a good way). As always, I’m not going to write a tutorial about any of these topics in detail, but give an overview of the most salient aspects of my learning (… I do intend on writing more focused tutorials in the near future).</p><p><a href="https://docs.swift.org/swift-book/LanguageGuide/Properties.html"><strong>Properties</strong></a><strong><br></strong>The Swift Language Guide states that, ‘<em>properties associate values with a particular class, structure, or enumeration</em>’. Properties can be stored i.e. store values in constants (let) or variables (var) or computed i.e. a value that’s the result of a calculation. Computed properties are provided by class, structure, and enumeration <em>types</em>. Stored properties are provided only by class and structure <em>types</em>. Properties can be associated with a <em>type</em> (i.e. a class) or an instance of a type (i.e. a class object).</p><p>In crude, simplistic terms… they’re the var and let values defined in classes, structures and enums. One thing to note… they’re not the same as global/local variables and constants i.e. a variable used in a for loop is a local variable. They’re specific to one of the 3 types mentioned.</p><p>The main things to know about stored properties is that if a value type is declared as a constant (i.e. structures/enums) then the var properties can’t be changed but this is not true for reference types (i.e. classes). So the below, would only work for a class instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d671d6c81813ab8e7d207d074bebee5/href">https://medium.com/media/9d671d6c81813ab8e7d207d074bebee5/href</a></iframe><p>Then there’s getters and setters (the code I’ve been finding confusing). Getters and setters are used to ‘get’ or ‘set’ a computed property and they’re written by putting a { after the property declaration (syntax that’s new to me); see below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c345e6a43d0f054c8152e6605a8f91bb/href">https://medium.com/media/c345e6a43d0f054c8152e6605a8f91bb/href</a></iframe><p>Now there’s a few ‘shorthands’ for setters and getters that really would baffle you if you didn’t read all about them like I have… honestly, it really pays to read the Swift Language Guide in its entirety. So first shorthand? Well you don’t need to define a name for a value passed to a setter as ‘newValue’ can be used in the braces by default. See below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79051fd17a878984c93246c92ad5666d/href">https://medium.com/media/79051fd17a878984c93246c92ad5666d/href</a></iframe><p>Another shorthand? If you only define a getter (i.e. you define a read-only property) then you don’t have to use the get keyword. See below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf9d3ad291939a5587f48f05ffd9ef18/href">https://medium.com/media/bf9d3ad291939a5587f48f05ffd9ef18/href</a></iframe><p>Finally, the other main thing to know about properties is a thing called ‘property observers’. These are things that ‘<em>observe and respond to changes in a property’s value</em>’… willSet is pass the new property value and didSet is passed the properties old value. I imagine they’re useful to implement when you want to know if a property value has change i.e. if you have a gameCompleted: Bool property and want to be notified when the game completes without having to check periodically using a function. Again, willSet and didSet also have some shorthands that are worth knowing about.</p><p>So properties… you should learn about stored vs. computed, getters and setters and willSet and didSet property observers and you’ll have a good broad handle on them!</p><p><a href="https://docs.swift.org/swift-book/LanguageGuide/Initialization.html"><strong>Initialisers</strong></a><strong><br></strong>According to the Swift Language Guide, ‘<em>Initialisation is the process of preparing an instance of a class, structure, or enumeration for use. This process involves setting an initial value for each stored property on that instance and performing any other setup</em>’.</p><p>To perform initialisation we use initialisers, which are ‘<em>like special methods that can be called to create a new instance of a particular type…their primary role is to ensure that new instances of a type are correctly initialised before they are used for the first time</em>’.</p><p>We actually used one earlier…a default initialiser:</p><pre>let newPerson = Person(firstName: &quot;Tim&quot;, age: 29)</pre><p>So, what’s the key stuff to know when it comes to initialisers? As already stated, classes and structures <strong><em>must</em></strong> set all of their stored properties to an initial value by the time an instance of them is created; this can be done within an initialiser or by using default property values when defining properties.</p><p>The below is a typical example of an initialiser that sets that properties of a type using the values passed into the initialiser as arguments when creating a new instance of that type, which in this case is a structure call Color.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5409509faadfe37467cc89a00d65f986/href">https://medium.com/media/5409509faadfe37467cc89a00d65f986/href</a></iframe><p>Swift provides a <em>default initialiser</em> (hidden to you) if you don’t define an initialiser yourself and so long as you provide default values for all of your properties. Structures also get a ‘<em>memberwise initializer’ </em>if you don’t define an initialiser yourself - this is the case even if you don’t provide default values either (don’t ask)!?</p><p>Initialisers can call other initialisers to perform part of an instance’s initialisation. This is called initialiser<em> </em>delegation, this is illustrated by the self.init() code within the second initialiser. The second initialiser takes a ‘<em>center</em>’ parameter and then users that to call an initialisers that takes an ‘<em>origin</em>’ parameter to fully initialise the Rectangle Structure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/729cca4c0e238a0b9daa5f989f72c8fe/href">https://medium.com/media/729cca4c0e238a0b9daa5f989f72c8fe/href</a></iframe><p>When it comes to structures and enums, delegation can only happen horizontally as they don’t support inheritance, unlike classes. If you have a parent/child classes then initialisation gets complex… seriously, there’s so much to read on the Swift Language Guide. However, a simplification below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/694c6f80ccbc38ea4510bab18f401865/href">https://medium.com/media/694c6f80ccbc38ea4510bab18f401865/href</a></iframe><p>Food is the parent class and has an initialiser that sets the property ‘<em>name</em>’. RecipeIngredient is a child class and has an initialiser which sets the property ‘<em>quantity</em>’ of the subclass and then calls the initialiser of its parent class, passing it the name value. There’s a lot more to it, but from what I can tell, this captures much of the essence.</p><p>Read about initialisation in all it’s glory <a href="https://docs.swift.org/swift-book/LanguageGuide/Initialization.html">here</a>.</p><h4>Coding Challenges &amp; Puzzles</h4><p>I didn’t do any… I guess my big ‘challenge’ was decrypting the horizontal scroll view code and tweaking it to make the image rotate relative to the scroll. I’ve had a busy week OK!? 😊</p><h3>What were the highlights?</h3><ol><li><strong>Understanding Complex Code Through ‘Play’</strong>.<strong> </strong>Much like a toddler learning about the world around them through play… I did the same but for learning about code. Also, by play I mean.. changing values and running the simulator over and over, printing everything to console, option + clicking everything. I learned an important lesson this week; if you don’t understand something then print it to console, then change it, then print it to console. Get hands on with the thing you don’t understand!</li><li><strong>Creating a Slick Onboarding Journey</strong>.<strong> </strong>I felt for the first time like I’d created (well replicated) something not to far from what you’d expect to see in a production app.</li><li><strong>Beginning to Remember How to Do Things</strong>. I have an awful memory, I really do, so it’s always feels rewarding when I remember something. I don’t have a specific example but there were a few times this week where I just did little things that I’d apparently learned like using optional binding to unwrap an optional or setting a constant as a delegate. There are a lot of things I don’t remember perfectly, but have learned enough to brute force my way to working code i.e. when writing the code to filter a dictionary above, it took me 30 mins to do it without Googling… but I got there! Most importantly, I’ll get there more quickly next time… and the time after.</li></ol><h3>What were the biggest challenges?</h3><ol><li><strong>Conceptualising Frames &amp; Bounds</strong>.<strong> </strong>It took me ages to understand bounds. I watched the tutorial over and over again and I didn’t feel like I got any closer to understanding the concept. It was frustrating to produce working apps that demonstrated scrollviews diligently, without actually understanding how it was working behind the scenes. I’m constantly finding that the quality of the resource and teacher makes all the difference when it comes to learning about concepts. The <a href="https://stackoverflow.com/questions/1210047/cocoa-whats-the-difference-between-the-frame-and-the-bounds">second answer on Stack Overflow</a> was the best explanation I eventually found.</li><li><strong>Maths</strong>.<strong> </strong>There was a lot of maths when it came to scroll views. It was simple math i.e. subtract 100pts (offset) from co-ordinate x (450pts) etc, but sometimes it’s hard to piece it all together. You have to know take into account the phones width, understand if scrolling left/right adds or takes away from the offset and move content by an amount relative to the scroll offset. It looks scary a first but they key is to just roll your sleeves up and keep running your code to see what happens!</li><li><strong>Lack of a Project</strong>. This week… I’m finding myself a project. I already have an ARKit project lined up but I need one I can work on now! I have plenty of ideas but none that totally captivate me… that will keep me up at night and spark a healthy obsession. I think to get better at coding, I need to work on a project to learn to solve problems myself vs. regurgitating what I see on a tutorial video.</li></ol><h3>Summary</h3><p>I enjoyed working with scroll views and have some more advanced things I’d like to do with them at some point. Firstly, I’m keen to create some kind of parallax scrolling app similar to the If This Then That example in one of the videos above. Secondly, I have an idea which involves moving scroll view B in a different direction to scroll view A when (+ at a speed that’s a multiplier of A), when scroll view A is scrolled… the below image kinda gives an idea of how I’d like to lay those scroll views out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0oSX2G63Vj6tQoV9w5aR6Q.png" /></figure><p>I’m also realising that my life has turned into product management, coding in my spare time, a cat called Clementine and mountain biking… but I’m OK with that!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NvBJAKeVzd2sbZ1nd1_8lA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*neZOjSX0ZX3K_-nDSVyECQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BNBFic__UbMZUARdyR7VLQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*isEaFPXsQ-Y0rfAl7HysBA.jpeg" /></figure><p>Much Love,<br>Tim</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36a4f14f135" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Taught Myself to Code - Week 5]]></title>
            <link>https://medium.com/@timothydplatt/how-i-taught-myself-to-code-week-5-caf6fee6d825?source=rss-296dc96c9045------2</link>
            <guid isPermaLink="false">https://medium.com/p/caf6fee6d825</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[product-design]]></category>
            <dc:creator><![CDATA[Tim Platt]]></dc:creator>
            <pubDate>Sat, 01 Sep 2018 09:52:04 GMT</pubDate>
            <atom:updated>2018-09-02T09:50:55.666Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C0gj8TABCAownWDo9j6TzQ.jpeg" /><figcaption>Current ‘Learning to Code’ Setup</figcaption></figure><h3>What did I do this week?</h3><p>I began the same way I’ve begun the last couple of weeks… reading about closures. It’s a construct I’ve been struggling to fully grasp for some time but the penny is finally starting to drop. I also played around with MapKit, completed a couple of HackerRank challenges and started Ray Wenderlich’s <a href="https://www.raywenderlich.com/5298-reproducing-popular-ios-controls">Reproducing iOS Controls tutorial</a>.</p><p>I’ve got a few ARKit tutorials I’m itching to try but I need a new iPhone so that I can run the augmented reality apps that I’ll build (you can’t run ARKit apps on a simulator as you need access to the camera); hurry along 12th September!</p><h4>Tutorials</h4><p>I completed a couple of MapKit tutorials by following Sean Allens <a href="https://www.youtube.com/watch?v=WPpaAy73nJc">Show User’s Location &amp; Permission</a>s and <a href="https://www.youtube.com/watch?v=2wxE8byc2FQ&amp;t=901s">Reverse Geocode to Get Address</a> tutorials. I chose these tutorials because I’ve not experimented with many different views so they allowed me to use new frameworks (MapKit &amp; Core Location) and a new view type (MKMapView).</p><p>I’ve simplified a few parts below because I don’t want my weekly blogs to explain what’s already been covered thoroughly in the tutorials I’ve followed.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPyOYIHjN87c%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPyOYIHjN87c&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPyOYIHjN87c%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0211d0c6fad6edd2cd0e897a61f5b22/href">https://medium.com/media/c0211d0c6fad6edd2cd0e897a61f5b22/href</a></iframe><p>There’s actually quite a lot to rendering a map showing the users location. Firstly we need to check if a users location services are active and available CLLocationManager.locationServicesEnabled() and check whether the user has authorised our app to use their location. If the authorisation status is not determined, we can ask the user for permission to use their location and if the user has agreed, we can startTrackingUserLocation().</p><p>We then created some methods to centre the map on the users location and to pass the users location to a function that provides a human readable address for the co-ordinates of that location. A users location is defined in terms of longitude and latitude and we use these values to create or receive co-ordinate values from a CLLocation object.</p><p>Finally, I fleshed out a function that was triggered when a user moves the map. The logic in the function checks whether the user moved the map by a significant amount and if they did it ‘reverse geocoded’ the longitude and latitude for the centre of the map, which is fancy way of saying “<em>got a human readable address</em>”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ca88fee1eceb7c308a5de0d1b22e07b/href">https://medium.com/media/1ca88fee1eceb7c308a5de0d1b22e07b/href</a></iframe><p>This function was also the first time I’ve consciously used a completion handler in my code (which is written as a trailing closure)! There’s still some stuff I don’t understand i.e. [weak self] or why updating the label goes inside DispatchQueue.main.async{} , but I’ll get to it.</p><h4>Reading</h4><p>Guess what I read about? Closures! Again. Specifically, I read about completion handers, which are closures that get passed to a function as an argument and then called when that function is done. So effectively completion handlers ‘<em>do something, when somethings been done</em>’ i.e. update a view once a successful API requests has completed or present an error once an unsuccessful API request has completed (see examples above). I’m actually going to try and explain them briefly below given how much I talk about them😬😬😬.</p><p>Firstly, imagine we want to use some method provided by Apple, we can’t see it’s inner workings but let’s suppose it’s a method that does some operations that may take some time:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b903d64eeb04c3312dffbfca3f2b6998/href">https://medium.com/media/b903d64eeb04c3312dffbfca3f2b6998/href</a></iframe><p>The reverseGeocodeLocation(_ location: <a href="https://developer.apple.com/documentation/corelocation/cllocation">CLLocation</a>, completionHandler: @escaping <a href="https://developer.apple.com/documentation/corelocation/clgeocodecompletionhandler">CLGeocodeCompletionHandler</a>) in the tutorials section is a great example of an Apple method that takes a completion handler and whose inner workings we can’t see.</p><p>Now, let’s suppose we are developing an app and when a the user taps the ‘register<em>’</em> button, we will create an instance of someBlackboxAppleClass and then call it’s createUser() method, passing in the users email and password.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/029a0083a19817670d6e877585d77625/href">https://medium.com/media/029a0083a19817670d6e877585d77625/href</a></iframe><p>createUser() is an intensive operation that takes some time and to prevent the interface from freezing while it happens, someBlackboxAppleClass performs the operation in the background. Therefore our app, specifically the method that called createUser(), needs a way to be notified once this background operation completes. To do this the createUser() method can be designed to take a function as a parameter, which its calls when the operation is completed i.e. a completion handler.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7672d01c7d8bb7a3777016dc992a10f/href">https://medium.com/media/c7672d01c7d8bb7a3777016dc992a10f/href</a></iframe><p>In the above, when all of the time consuming process have completed, the completion handler function is called and is passed whether the operation was a success and a userID (which may be nil if the operation failed).</p><p>Let’s call this method in our app again. However, we also need to create the function in our app that we’re going to pass to the createUser() method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/445104781b5affee38fdaa9c6777d236/href">https://medium.com/media/445104781b5affee38fdaa9c6777d236/href</a></iframe><p>Instead of having a completed function, passing that to createUser and then having that be called from createUser once the operations complete, we can just pass it into the createUser function call as a closure. So let’s convert the completed function into a closure by deleting the function name and func keyword and moving the opening brace to the start of the closure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f58e9bb12103399cc7e7ff8330a2c6b2/href">https://medium.com/media/f58e9bb12103399cc7e7ff8330a2c6b2/href</a></iframe><p>Then let’s pass the closure in the method call:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16a9f88ff4013ac142955b91b082ee8c/href">https://medium.com/media/16a9f88ff4013ac142955b91b082ee8c/href</a></iframe><p>As it’s the last parameter being passed to the method, we can write the method call using a trailing closure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c900930561bdb7b9e9564d68d306d0e/href">https://medium.com/media/1c900930561bdb7b9e9564d68d306d0e/href</a></iframe><p>Finally, let’s run the above:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a992699252351e7dfbf98014d6115b25/href">https://medium.com/media/a992699252351e7dfbf98014d6115b25/href</a></iframe><p>It may seem like a lot, but in your code you‘re much more likely going to use the createrUser() functionality (i.e. Apple methods) as opposed to define them yourself so 99 times out of 100 you’ll only be writing the code in the registerButtonTapped() function. The complete code is below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf464970e62841e148409440209d5fc7/href">https://medium.com/media/cf464970e62841e148409440209d5fc7/href</a></iframe><h4>Coding Challenges &amp; Puzzles</h4><p>I completed two HackerRank challenges this week. The first:</p><p>Given two strings, determine if they share a common substring. A substring may be as small as one character. For example, the words “a”, “and”, “art” share the common substring &#39;a&#39;. The words “be” and “cat” do not share a substring.</p><p>I had to complete the task by developing the logic within an empty function. I’ve been doing these challenges in Java because I learned quite a lot of fundamentals from the <a href="https://courses.caveofprogramming.com/p/java-for-complete-beginners">Java for Complete Beginners</a> course I completed in my first week of coding and I figure it keeps me fresh in Java too. My submission is below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d1f1fd06f4cc1604bac2d6831db51d1/href">https://medium.com/media/1d1f1fd06f4cc1604bac2d6831db51d1/href</a></iframe><p>I realised afterwards I could have checked if the .size() of characterSet1 was greater than 0 after doing characterSet1.retainAll(characterSet2), which results in a set containing only elements common in both sets.</p><p>The second challenge took me 4 hours, lot’s of Googling. The challenge was:</p><p>Two strings are anagrams of each other if the letters of one string can be rearranged to form the other string. Given a string, find the number of pairs of substrings of the string that are anagrams of each other.</p><p>When I started this challenge I honestly didn’t have a clue what to do. Fortunately, I saw on a discussion board that a C++ programmer state how he had felt the same, but then he decomposed the challenge into smaller problems and then pseudo coded solutions to each smaller problem before pulling it altogether. This advice really helped me a lot! I often find myself not knowing where to begin with such challenges.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/252b10726ac4f44cf540a25ba621de9a/href">https://medium.com/media/252b10726ac4f44cf540a25ba621de9a/href</a></iframe><p>I noticed that a lot of people solve the challenge above in a variety of ways, it was interesting how different people take different approaches to the same problem.</p><h3>What were the highlights?</h3><ol><li><strong>Visible Progress</strong>. I feel like I’m making steady progress and I see evidence of this i.e. being able to write about closures, being more comfortable reading code or adapting others code. It’s quite easy to become discouraged when learning to code as the learning curve is so steep, which is why I think it’s important to give yourself some kudos because it’s generally a hard slog and it’s easy to feel like you’re getting nowhere.</li><li><strong>Interactions With Developers</strong>.<strong> </strong>I’m luck enough to have a few friends who are iOS developers that show an active interest in my development and it honestly gives me a mental boost knowing when experienced developers are giving you a encouragement. Shout out to <a href="https://medium.com/u/4a3f8e892015">Alex Trott</a> and @RobRWApp.</li><li><strong>Learning Diversity</strong>.<strong> </strong>I completed some HackerRank challengers in Java and had some moments of ‘organic tinkering in Xcode’ and it made me realise that it’s important to make sure your learning is diverse… a mix of tutorials, experimentation, time-boxed challenges etc. The best teams are those with a diversity of people and thought, the same is true of learning approach.</li></ol><h3>What were the biggest challenges?</h3><ol><li><strong>Self Motivation</strong>.<strong> </strong>I’m working pretty hard, but I also feel like I could be working harder, or perhaps smarter; improving my capacity to retain information for instance or focusing better . I tend to reply to e-mails, follow rabbit holes reading about new words/constructs that I’ve not covered before etc. I downloaded Forest app, which I’m planning to start using from next week onward.</li><li><strong>Quality of Resource Available</strong>.<strong> </strong>I’m still finding there to be a lot of disparity in quality of resource. In general a lot of iOS resources are either quite dated (especially since the continued move to Swift) or gloss over the basics and get technical very quickly. There’s a lot of awesome people producing lot’s of great educational content and I hope I can support that movement soon, but it’s still a bit of a tricky landscape to navigate as a novice.</li><li><strong>Knowing Where to Begin</strong>. When it comes to the HackerRank challenges it’s often hard to even know what to begin doing or typing (I’ve become somewhat accustomed to watching videos and following along). This is why problem solving skills are held in such high regard in the software engineering field. My recommendation here is to put pen to paper; code is so abstract that sometimes it’s good to doodle a tangible representation of the problem; I do this a lot when I have nested loops or 2D arrays because my brain struggles to conceptualise these without sketching them out. Or even think about the coding problems you have as analogous real life problems; Swift guidelines for instance explain the concept of optionals by using a physical box that may or may not contain items as an example.</li></ol><h3>Summary</h3><p>This week I did a mix of things… tutorials, reading, challenges, writing about what I learned etc and I definitely feel like the diversity of learning is a positive. I’ve realised a couple of important things this week:</p><ol><li>Have a plan! To maximise your time, go into the week with a lost of tutorials you want to complete and schedule them into your calendar. When I was following Angela Yu’s tutorials, it was very structured and I just popped open my browser and Xcode and got in with coding. You don’t want to waste your ‘working time’ searching around for tutorials and figuring out what to learn next.</li><li>I’m starting to feel like I need my own project to work on. Firstly, I feel I need to move away from following tutorials and regurgitating what the tutors tell me to. Secondly, I need something I can’t put down…if I’m working on my own project I’ll have a natural emotional investment in that project and it will incentivise me to problem solve with that much more tenacity.</li><li>Have fun, exercise and step away from the keyboard when things get a little frustrating!</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i1E2I7vEXbrknMI9GolE7Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6zCbJprr83MRl4C32fYLkQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P6eKTXBVWBEOGWcotdGsAQ.jpeg" /><figcaption>Unwinding with a bike ride and Clementine providing moral support/companionship as always.</figcaption></figure><p>Don’t give up!<br>Tim</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=caf6fee6d825" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Taught Myself to Code - Week 4]]></title>
            <link>https://medium.com/@timothydplatt/how-i-taught-myself-to-code-week-4-37ee6759714?source=rss-296dc96c9045------2</link>
            <guid isPermaLink="false">https://medium.com/p/37ee6759714</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Tim Platt]]></dc:creator>
            <pubDate>Tue, 28 Aug 2018 16:04:49 GMT</pubDate>
            <atom:updated>2018-08-28T16:07:04.918Z</atom:updated>
            <content:encoded><![CDATA[<h3>What did I do this week?</h3><p>I didn’t have my most productive week and I put this down to two things; firstly I didn’t plan my week and secondly I took a lot longer than I anticipated to get my head around some of the concepts I studied. Perhaps I’m too hard on myself?</p><h4>Tutorials</h4><p>I completed 3 CoreML modules from Angela Yu’s <a href="http://udemy.com/ios-11-app-development-bootcamp/">iOS App Development Bootcamp</a>, they were:</p><ul><li>Introduction to Machine Learning.</li><li>CoreML - How to Incorporate Machine Learning into Your iOS Apps.</li><li>Advanced CoreML - Convert Pre-Trained Models Using CoreML Tools.</li></ul><p>CoreML is a machine learning framework that allows iOS developers to integrate trained machine learning models into their apps. A model is the artefact created from providing a machine learning algorithm with training data to learn from; a model then makes predictions based on new input data. For example, a model that’s been trained on a cities historical house prices may be able to predict a house’s price when given the number of bedrooms and a post code as input.</p><p>Apple provides a number of <a href="https://developer.apple.com/machine-learning/build-run-models/">ready made models</a>. Following Angela’s tutorials, I used Core ML (machine learning framework), Vision (image analysis framework) and Inception v.3 (a pre-trained object detection model) to determine whether an object I took a picture of was or wasn’t a hot dog 🌭!?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F31BBbjDwI5w%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D31BBbjDwI5w&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F31BBbjDwI5w%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d23129312c9545fbe15203a51f0de8c/href">https://medium.com/media/9d23129312c9545fbe15203a51f0de8c/href</a></iframe><p>I’m unable to side-load (i.e. install apps I develop) on my physical device as it’s locked down, so I instead had to download the pictures of hotdogs and drag them from my desktop to the simulators photo app library. I then had to create a imagePickerController object and make it’s source type .photoLibary vs. .camera too as the simulator doesn’t give you camera functionality.</p><p>The tutorial also involved embedding the view in a NavigationController (we placed the camera icon in the navigation), conforming to two interfaces, asking for users permission to access their images, creating a container for our model and making a request for the model to analyse the image an provide a result (prediction what the image is). All this with ~70 lines of code!?</p><p>Next, I created an app that can identify flowers! I did this by converting a pre-existing model that was created using a different tool called Caffe into a model that is CoreML friendly (an MLModel). It appears like Apple offers a limited number of ready made object detection models but academics have historically (and continue) to use other tools like Caffe, Tensor etc to create models. It seems like a lot of model conversion tools are available to bridge the gap. This involved installing a tool called ‘<a href="https://pypi.org/project/coremltools/">coremltools</a>’ and then running some python to convert a Caffe model to a MLModel.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FUDHJYHL5fxU%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DUDHJYHL5fxU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FUDHJYHL5fxU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ddb518a2938b35da4725b449f80b1f3/href">https://medium.com/media/0ddb518a2938b35da4725b449f80b1f3/href</a></iframe><p>Finally, I completed the loop and created my own model! Apple acquired a company call Turi, which provide a tool called Turi Create that allows users to create custom ‘ModelML’ models that are the right format to use with the CoreML framework. Not only that, it makes it simple for those with little or no experience with machine learning to build a model fit for their need by following a very simple set of steps. Naturally I chose to create an app that detected 🍺 types!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJbCvw2MxdfE%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJbCvw2MxdfE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJbCvw2MxdfE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/43e8f959bc96844a39f37101bf63fe50/href">https://medium.com/media/43e8f959bc96844a39f37101bf63fe50/href</a></iframe><p>I think CoreML still has someway to come before it’s more widely adopted in mainstream apps i.e. the ability to continuously train the model would make it quite powerful. For example, imagine making a dating app, where the model learns peoples ‘type’ over time, as the user swipes through matches… I’m sure Tinder has such technology, but imagine if that king of sophisticated learning was available to your average developer!</p><h4>Reading</h4><p>I planned to better understand different methods of passing data around in iOS and aimed to read about closures, delegation, segues &amp; notifications. However, I only covered closures and delegation, but I spent a significant amount of time on each, making sure that I was able to follow the syntax and fully understand these constructs (I’m still not quite there yet)!</p><p><strong>Closures<br></strong>It’s worth noting that Closures are an intermediate topic and you shouldn’t beat yourself up if you take a while to get your head around them. Closures are described by Apple as, “<em>self contained blocks of functionality that can be passed around and used in your code</em>”, so functions then!? Kind of.</p><p>The <a href="https://docs.swift.org/swift-book/LanguageGuide/Closures.html">Swift Language Guide</a> is my default starting point when learning about any Swift construct and should be yours too. I would then recommend this selection of awesome reads (and reading each multiple times):</p><ul><li><a href="https://medium.com/the-andela-way/closures-in-swift-8aef8abc9474">Closures in Swift</a> by <a href="https://medium.com/u/ad7cd39bffc7">Angela Mugo</a>.</li><li><a href="http://Closures in Swift: The sequel">Closures in Swift the Sequel</a> also by <a href="https://medium.com/u/ad7cd39bffc7">Angela Mugo</a>.</li><li><a href="https://medium.com/@abhimuralidharan/functional-swift-all-about-closures-310bc8af31dd">Functional Swift: All about Closures</a> by <a href="https://medium.com/u/57bc6d94b8f0">Abhimuralidharan</a>.</li><li><a href="https://www.bobthedeveloper.io/blog/no-fear-closure-in-swift-with-bob">Closures in Swift</a> and <a href="https://www.bobthedeveloper.io/blog/completion-handlers-in-swift-with-bob">Completion Handlers in Swift </a>by <a href="https://medium.com/u/89e88798c91b">Bob Lee</a>.</li></ul><p>The high-level concepts to try and understand when it comes to closures are:</p><ul><li>Closure expression syntax.</li><li>Trailing closure syntax.</li><li>Capturing, referring to and modifying values in surrounding context.</li><li>Completion Handlers.</li><li>Escaping closures.</li></ul><p>The absolute starting point when it comes to understanding Closures, is getting a grasp of the closure expression syntax, which can be quite confusing if you try to read it without any context. It’s well worth reading the Swift language guide to understand how Closure expression syntax is optimised into such a brief (sometimes clear) style. See an example below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9e628f6df3446f223cdea61557b457d/href">https://medium.com/media/c9e628f6df3446f223cdea61557b457d/href</a></iframe><p>After getting my head around the closure expression syntax I then looked at trailing closures. If you pass a closure expression to a function as the functions final argument, trailing closures can be a more readable way of passing the closure, especially if the closure is long.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/223f5f6010e21ade22131ebcffc8bc15/href">https://medium.com/media/223f5f6010e21ade22131ebcffc8bc15/href</a></iframe><p>I then spent a LOT of time learning about completion handlers as they’re used in a lot of places in iOS development i.e. saying what to do after animating from screen A to screen B or after downloading something from an API… or in simple terms they “<em>do something, when something’s completed/failed</em>”. I recommend reading Bob Lee’s articles to better understand them as they’re too complex to explain in my little blog!</p><p><strong>Delegatation<br></strong>I spent a lot of time on delegation as this communication pattern is also very prevalent in iOS development. Essentially, delegation is,</p><blockquote>A pattern in which one object in a program acts on behalf of, or in coordination with, another object. The delegating object keeps a reference to the other object–the delegate–and at the appropriate time sends a message to it. The message informs the delegate of an event that the delegating object is about to handle or has just handled. The delegate may respond to the message by updating the appearance or state of itself or other objects in the application.</blockquote><p>Again, I don’t intend to explain the delegation in my weekly blog as it’s a huge topic that requires a dedicated post, but I do intend to shorten your time to learn this pattern by pointing you in the direction of these recommended reads:</p><ul><li><a href="https://www.appcoda.com/swift-delegate/">Swift Delegate</a> by Andrew Jaffee.</li><li><a href="https://www.youtube.com/watch?v=DBWu6TnhLeY">Swift Delegate Protocol Pattern</a> by Sean Allen.</li><li><a href="https://www.youtube.com/watch?v=ekQ0pqzc9Kg">Passing Data with Delegates</a> by Mark Moeykens.</li></ul><h4>Coding Challenges &amp; Puzzles</h4><p>I didn’t do any formal challenges this week but I did do some ‘organic’ exploring of UITabBar. Why? Firstly, I’ve not experimented much with the user interface during my tutorials and secondly, I wanted to see if I could configure a tab bar from what I’ve learned goofing about with other view controllers.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6-aa9paBp3k%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6-aa9paBp3k&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6-aa9paBp3k%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a722d21aa48fb777557df6fc75b96ed/href">https://medium.com/media/1a722d21aa48fb777557df6fc75b96ed/href</a></iframe><p>The main things I learned were to style the TabBar in the UITabBarController:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2e7d02086ef0d5738a7e331dbd80ced/href">https://medium.com/media/b2e7d02086ef0d5738a7e331dbd80ced/href</a></iframe><p>I also learned how to style other tab bar items when the app launches by writing code within the viewDidLoad function of the first view controller presented by the UITabBarController (a TabBarController accepts an array of UITabBarItems and loads the view controller in index 0).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28d28e6ae9d7affcef20206d8d6a01b6/href">https://medium.com/media/28d28e6ae9d7affcef20206d8d6a01b6/href</a></iframe><p>You can also add similar text as the above to other view controllers but the UITabBarController will not style the tab bar or it’s items until that view is loaded by tapping on it in the tab bar.</p><h3>What were the highlights?</h3><p><strong>1. CoreML</strong>. It was pretty awesome creating an app that is able to classify an object using machine learning and it was interesting seeing how algorithms break an object down into a list of possible classifications ordered by confidence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZYp7x17vZqkLOWBtJw9t8Q.png" /><figcaption>A sample of results from the hotdog c</figcaption></figure><p>I loved the fact I was able to do something that is considered so complex with so little ease, it makes machine learning accessible to everyone, which is no small feat. However, I also didn’t really learn about CoreML because it abstracts you so much from what’s going on under the hood.</p><p><strong>2. Beginning to understand complex concepts i.e. closures &amp; delegates. </strong>It’s taken me a while to wrap my head around closures and delegates but I’m getting there! I think the secret recipe is persistence. I would miss something each time I read an article and learn a little more by copying different authors code into Xcode playground and following it meticulously. Bob Lee made me feel better about myself too, he’s a pretty awesome developer and he makes no secrets about the fact it took him months to learn these things.</p><p><strong>3. I had great company!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Hys5vIsW6Py0peWa3wqmw.jpeg" /></figure><h3>What were the biggest challenges?</h3><ol><li><strong>Collecting data need to create a decent model</strong>.<strong> </strong>I want to make a more complete version of my beer identification app but I need 100’s of images for every beer and there’s no readily available datasets. I’d also need to release a new app version every time I update the model (i.e. added in new beers that my app could detect), which would be lame for the user.</li><li><strong>Gap between theory &amp; real world</strong>.<strong> </strong>I’m still finding the examples on the tutorials quite far removed from the IRL uses in a typical iOS project but I’m making a conscious effort to build apps in Xcode to bridge the gap.</li><li><strong>Installing TuriCreate</strong>. I spent as much time installing TuriCreate as I did building the beer identification app! In short, <a href="https://www.pythonforbeginners.com/basics/how-to-use-python-virtualenv">create a virtual python environment</a> and install TuriCreate from their otherwise it’ll probably keep failing. Angela Yu covers this in her CoreML tutorials.</li></ol><h3>Summary</h3><p>I guess I did quite a lot given I declare week 4 ‘not my most productive’. I would highly recommend getting your hands dirty with CoreML as it’s a great way to build an advanced app without needing to be a machine learning expert! It will give you a great sense of satisfaction. Additionally, keep trying to master the scary stuff, that may not seem in reach i.e. closures, delegation etc. As far as I can tell, these things are essential if you want to become a professional iOS developer and just require some persistence (if this average dude can learn these things, so can you)!</p><p>Big Loves,<br>Tim</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37ee6759714" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is a Product Manager? A different perspective]]></title>
            <link>https://medium.com/theuxblog/what-is-a-product-manager-a-different-perspective-b2e82a2a3801?source=rss-296dc96c9045------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2e82a2a3801</guid>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[startup]]></category>
            <dc:creator><![CDATA[Tim Platt]]></dc:creator>
            <pubDate>Wed, 12 Oct 2016 15:33:00 GMT</pubDate>
            <atom:updated>2016-10-14T01:06:21.901Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*d7Jnng0wX2Qqqsy20DOADg.jpeg" /></figure><p>For as long as I have been a product manager the role of ‘product manager’ has been the subject of much debate — specifically, what is a product manager? It’s important for a role to have definition otherwise it’s unclear how you do great in that role. It’s also difficult to understand how and where you fit in the organisation and for others to understand how they interface with you in the absence of a clear definition.</p><p>I am aware that a the role of ‘product manager’ has proven one of the more difficult to write a formal ‘<em>specification</em>’ for and it’s a role that has been bastardised as organisations have introduced the role type/title without fully understanding it, often in reaction to those that have gone before them. It’s a role that’s been confused by recruiters that have been tasked with hiring for a diverse range of jobs that have been forcibly preceded or appended with the word ‘product’. It’s even been rebranded many times over within the product community — older terms such as ‘<a href="http://pragmaticmarketing.com/resources/cage-fight-product-owner-vs-product-manager">product owner</a>’ now carry disdainful undertones or ‘customer evangelist’ add superfluous vagueness.</p><p>What I do firmly believe however, is that the role that we have come to refer to as ‘product manager’ is very important to the success of the product and that a great product manager will deliver considerable value to your customer and to the organisation. This belief was reinforced upon hearing a speech by Marty Cagan called ‘<a href="http://svpg.com/behind-every-great-product/">Behind Every Great Product</a>’ — he did something that I’d previously struggled to do and that is to articulate my belief in the importance of what we know as a ‘product manager’ in a way that was consumable by anyone and everyone.</p><blockquote><em>What has not changed is my overarching belief that behind every great product, there is someone, usually someone behind the scenes, working tirelessly, that is playing this critical role. They usually have the title ‘product manager’ but they might be a startup co-founder or the CEO, or they might be in another role on the team and stepped up because they saw the need. The title is not important; the work they do is. — Marty Cagan</em></blockquote><p>Think about that, “<em>the title is not important; the work they do is”</em>. I think Marty sums it up better than I ever could. Another important statement in that quote is that, “<em>They usually have the title ‘product manager’ but they might be…in another role</em>”, let’s talk about this because it’s important. Firstly, having the job title ‘product manager’ doesn’t by default mean that you’re the person Marty is describing and nor does it mean that the success of a product comes down to the merits of a single individual or job role. I couldn’t care what role title I am given, it wouldn’t change my motivation or willingness to step up to make that product a success. I know that behind the great products I work on — there’s a team of individuals who are all ‘product managers’ by the above definition, even if it’s not what’s listed in the HR system.</p><h4>So what does a great ‘product person/team’ look like?</h4><p>So far I’ve asserted a couple of notions — the first is that the role we typically refer to as ‘product manager’ is an important, crucial and very real role. The next, that the title per se is not important but as Marty rightly identifies…the work they do is; that’s the winning ticket.</p><p>Roles are typically articulated by listing the responsibilities, skills and character traits an individual would be expected to exemplify were they do be someone that could grow, shine and perform in that role. The role’s title is important in that it serves as a proper noun against which we can articulate these things. It’s always been something that again that we’ve struggled to codify — often resulting in fluffy terms such as ‘CEO of the product’ or ‘ambassador for the user’, which doesn’t help anyone. Aren’t we all?</p><p>So if the role title isn’t important but the person and the work they do is then what sort of person should we be looking for? What skills and traits should they hold? How would we know a what good looks like? In all honesty, I couldn’t begin to sum that up in a way that would be succinct or complete (or that wouldn’t need later refactoring when I stumble across some better analogy, adage or adjective).</p><p>I stated earlier that it’s important for a role to have definition. What I’m not going to do is write that as some kind of specification — typical of what you may find on an organisations recruitment portal (<em>owns the backlog, prioritises features, communicates effectively with stakeholders etc</em>). The specifics will vary organisation to organisation. However, what I’m going to take a punt at doing is specifying what some of those traits, characteristics and mindsets are that make a great product person. If you choose to decant from this a bullet point list of responsibilities and hard requirements then do so, but at a minimum I hope that the below puts that list into context.</p><p>So what traits, characteristics and skills does a great individual behind any great product embody? I’m going to answer that using the analogies, anecdotes, adjectives and adages that I’ve stumbled across and have personally found to hold true:</p><p><strong>1. Multi Disciplined</strong>: There is an overused venn diagram that’s often referenced when describing the product manager role — it places product managers at the intersection between business, technology and UX. This does not mean that a product manager will be a unicorn, someone that is exceptional across all three of these dimensions. It also doesn’t mean that the product manager will be equally balanced across these three dimensions. Finally, it also does not mean that an engineer or a designer couldn’t make a great product manager, they may spike more heavily on certain dimensions but they may also be strong on the other dimensions too. In the wise words of <a href="http://www.mindtheproduct.com/2011/10/what-exactly-is-a-product-manager/">Martin Eriksson</a> a product manager should be:</p><blockquote>Experienced in at least one, passionate about all three and conversant with practitioners in all. — Martin Eriksson</blockquote><p><strong>2. A leader &amp; an influencer; without authority:</strong> When we use the term ‘CEO of the product’ we should use it lightly, because a product manager often doesn’t (and shouldn’t) have authority over those that are crucial to the development and evolution of a product. Instead, we often find the great people behind great products possess the ability to rally those around them, those with tools and skills they don’t necessarily hold to solve for a need that has been identified (or even identify a need in the first instance).</p><p><strong>3. Makers:</strong> The people behind great products have a tendency to be makers and if they’re not makers by mould then then they should aspire to be so. OK, but WTF is a maker?</p><p>A maker to me is simply someone who makes or produces tangible things in order to bring ideas to life. The power of ‘making’ is that it gives those with little context as to the problem your trying to solve (or the solution you’re trying to articulate) something that they can interact with to piece together their own understanding. The benefits of ‘making’ are multifold:</p><ul><li>You begin with a solution that is somewhat ignorant of constraints, which allows you to explore possibilities that you may not approach were you to start by doing all of your analyses and eliciting stakeholder input up front.</li><li>You have your first iteration — it’s probably far from perfect and you should be prepared to reconstruct it or throw it away entirely but in the process of making you will have learned something (and learned it well in advance).</li><li>It changes conversations with stakeholders from “‘you can’t do that/that’s not possible” to “how can we support you/oh, you’ve begun to figure it out”. Oftentimes, it’s hard for those not close to the product or in different disciplines to visualise what you’re trying to articulate through words, user stories etc alone.</li><li>The final reason why being a maker is so important to me and valuable is this — the phrase ‘meet user needs’ is valid but it conceals some important truths. Users <a href="https://en.wikipedia.org/wiki/Nicholas_J._Belkin">can’t always articulate their needs</a> and <a href="http://designingsocialinterfaces.com/patterns/Pave_the_Cowpaths">some don’t even know what there needs are</a> in order to articulate them. Users sometimes can’t imagine a certain reality or realise they had a need unless you explore, prototype and create new things for them to interact with.</li></ul><blockquote><em>Humans do two things that make us unique from all other animals; we use tools and we tell stories. And when you make something, you’re doing both at once.</em></blockquote><p>You may be thinking — but I’m not a designer or a coder, how can I be a maker? You don’t need to be proficient any design or coding to be a maker. Anyone can make a prototype using pen and paper. You should never underestimate the power of a sketch in any fidelity. Additionally, some people are blessed with the gift of being excellent story tellers and are able to make things tangible through words, presentations and other mediums. An important mindset of design thinking is to ‘show, don’t tell’. I’d encourage anyone now familiar with design thinking to get to be so.</p><p>We often hear product managers referred to as orchestrators. While this analogy has it’s merits I think the value is really realised when an individual can switch between ‘making’ and ‘orchestrating’. At a minimum, if you’re not a maker but you work with people that are, the best thing you can go is <a href="http://www.paulgraham.com/makersschedule.html">respect their schedules</a> and how they work.</p><p><strong>4. Building the right thing vs building the thing right</strong>: Both are valuable, however it is crucial to have great people working their magic behind the right solution — and if not, you need to be able to identify so and pivot. It’s easy to get going on the wrong thing. I want to stress again, you should care as much about building the thing right but it’s a pre-requisite to a successful product that you’re building the right thing in the first instance.</p><p>Sometimes we have a magpie tendency and go for the shiniest work, sometimes we identify a valid problem to solve but don’t keep tabs on whether that problem still exists and sometimes we misinterpret data and get going down the wrong path. To be a great person behind a great product, you need to have the ability to tease out what the right problems are that need solving and when you do, focus on solving them properly.</p><p><strong>5. Divergent/convergent thinkers</strong>: Great product people (note, I’ve not been using the term ‘product managers’) are able to vary their thinking between being ‘bigger picture’ and ‘action oriented’. In design thinking the phrases ‘flaring’ and ‘focusing’ are used to refer to the different types of thinking and to frame the elements of an effective brainstorming process. Different ‘stokes’, methods and tools and embracing a design thinking mindset are used to facilitate moving between these modes of thinking.</p><blockquote>‘Brainstorming, out-of-the-box thinking, and radical innovation’ are a few of the buzz words that may come to mind. All of these words fall under the category of ‘flaring’ — thinking widely to incorporate unusual solutions, offbeat ideas, and to expand the solution set as widely as possible before narrowing down to one. — Jude Fulton</blockquote><p>Flaring must be paired with moments of acute focus, in order to learn and move quickly. We all have a tendency towards one way of thinking over another and that’s fine. In fact it’s important to have people who are awesome at both of these things. However, it’s also great to have people behind your product that are adept at doing both.</p><p><strong>6. Pragmatism (in sprinkles)</strong>: I was told when I first started out as a product manager that the hardest part (but one of the most important parts) of the role was being able to say no. It still holds true today. It’s hard to say no, even when it’s the right thing to do. It also takes courage to say yes, even when it’s a scary thing to do, maybe something no one’s done before. A good product person can make the right call (and is willing to) when those decisions need to be made.</p><p>The ‘I shouldn’t use Wikepedia but I did anyway’ definition of what it means to be pragmatic is to ‘do what works best’. This is why I put ‘in sprinkles’ in brackets.</p><p>It’s not always that black and white. What works best differs depending on the lends through which you’re viewing things. What’s best for the organisations bottom line isn’t always what’s best for the customer. The best solution isn’t always one that will work best in a few months time. What’s technically feasible will sometimes mean compromising the design, which doesn’t work best for the designer or maybe the user.</p><p>Unfortunately, we have to make calls that are the lesser of evils. We’re often put between a rock and a hard place and it’s the ability to make and rationalise these decisions in a way that works for the greater good that is an important trait to have. Equally, it’s also knowing when ‘what works best’ isn’t good enough and being able to set and define a minimum benchmark against which to hold true. This is where having clear principles can go a long way.</p><p><strong>7. Trust their experts for their expertise</strong>: A great person behind any great product knows that they alone do not have all of the skills and bandwidth to make a great product. I think it’s safe to say that behind ever great product their is a great team and behind every great product person there’s a great support network.</p><p>I borrowed a quote earlier from Martin Eriksson that outlined that a product manager is, “Experienced in at least one, passionate about all three and conversant with practitioners in all” with regards to their understanding of business, design and technology. A great product person is able to identify gaps in their domain knowledge and collaborate with others that have strengths in that area. A great product team will be greater than the sum of it’s parts as a result.</p><p><strong>8. Love what they do. Love who they do it with. Love who they do it for</strong>: I stole this from <a href="http://www.rdoconference.org/wp-content/uploads/2016/03/BJ-Cunningham-Profiting-from-the-Truth.pdf">BJ Cunningham</a> because it sums things up pretty damn well. We all know great product people are supposed to care about the end users. We all know great teams are those that have a great rapport and relationship with one another. We all know that an organisation should have a mission that you believe in and can rally behind, one that gives you purpose.</p><p>However, you can’t make someone love what they do or who they do it for by telling them that they should. You can’t just state a mission and expect people to simply rally behind it. You can’t say your user driven and then ignore the customer when it comes to crunch time.</p><p>A great product person lives and breaths these emotions. They are infectious. They bring the importance of the product to life. They bring purpose into the everyday. They love what they do because that’s how they feel, not because they are supposed to. They love empowering others so that they can feel this way too.</p><p>You can tell people to love what they do, who they do it for and who they do it with. You can to some extent create environments that encourage those emotions. Or you can make sure you have individuals on your team that innately feel this way and hope their feverish passion spreads.</p><h4>To summarise</h4><p>The term ‘product manager’ is simply a title. The title is necessary but somewhat irrelevant, what isn’t irrelevant is the work the person/teams do and the mindset and traits they they display. I truly believe that behind every great product, is a great person or team. I think Marty is on to something here.</p><p>Sometimes we obsess about what our roles are (vs. who we serve) and what we are responsible and accountable for. It makes sense for sure to have clearly defined responsibilities, however sometimes we place too much emphasis on the definition. We want to codify things into responsibilities and bullet pointed lists vs. focusing on developing the mindsets and ways of thinking synonymous with great product people.</p><p>Can anyone do the role? Yes. Does that mean they’ll be great at it? No.</p><p>As people leaders your role isn’t to create the role of product manager but it is to enable those within your organisation to flourish by establishing the best environment, nurturing a great culture and equipping them with the autonomy and tools to become great people behind what will ultimately be a great product.</p><p>Oh, and how do we rewards those great people/teams? The product in itself is a reward for those that love what they do, who they do it with and who they do it for.</p><p>Finally, for those of you that can’t deal with the fluff of it all. If you really must have a more tangible way of articulating what a great product person embodies and exhibits then this is <a href="https://medium.com/@johnpcutler/the-evolving-product-manager-role-6f288bbc3cda#.5un2q8nj0">the list I personally hold myself accountable against</a>.</p><p>Tim Platt (Maker)</p><p><a href="https://powered.by.rabbut.com/p/yBBt?c=4">Subscribe to The UX Blog</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2e82a2a3801" width="1" height="1" alt=""><hr><p><a href="https://medium.com/theuxblog/what-is-a-product-manager-a-different-perspective-b2e82a2a3801">What is a Product Manager? A different perspective</a> was originally published in <a href="https://medium.com/theuxblog">theuxblog.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>