<?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 Seab Jackson on Medium]]></title>
        <description><![CDATA[Stories by Seab Jackson on Medium]]></description>
        <link>https://medium.com/@seabjackson?source=rss-8df11fc7fc9c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Seab Jackson on Medium</title>
            <link>https://medium.com/@seabjackson?source=rss-8df11fc7fc9c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 03:12:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@seabjackson/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[Model View Controller (MVC)]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@seabjackson/cs193p-developing-ios-11-apps-with-swift-lecture-2-notes-bad3318aedde?source=rss-8df11fc7fc9c------2"><img src="https://cdn-images-1.medium.com/max/1986/1*Thq9Q3M_6rHwYm0VNNjyGA.png" width="1986"></a></p><p class="medium-feed-snippet">CS193P: Developing iOS Apps with Swift</p><p class="medium-feed-link"><a href="https://medium.com/@seabjackson/cs193p-developing-ios-11-apps-with-swift-lecture-2-notes-bad3318aedde?source=rss-8df11fc7fc9c------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@seabjackson/cs193p-developing-ios-11-apps-with-swift-lecture-2-notes-bad3318aedde?source=rss-8df11fc7fc9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bad3318aedde</guid>
            <category><![CDATA[mvc]]></category>
            <category><![CDATA[cs193p]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Seab Jackson]]></dc:creator>
            <pubDate>Tue, 16 Jan 2018 04:44:44 GMT</pubDate>
            <atom:updated>2018-02-04T13:36:45.833Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[CS193P: Developing iOS 11 Apps with Swift 4 lecture 1 notes]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@seabjackson/cs193p-developing-ios-11-apps-with-swift-4-lecture-1-notes-97731bd7862?source=rss-8df11fc7fc9c------2"><img src="https://cdn-images-1.medium.com/max/2600/1*UlybzoOkP5X87QLW7e7Hwg.png" width="2624"></a></p><p class="medium-feed-snippet">Building a Concentration Game</p><p class="medium-feed-link"><a href="https://medium.com/@seabjackson/cs193p-developing-ios-11-apps-with-swift-4-lecture-1-notes-97731bd7862?source=rss-8df11fc7fc9c------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@seabjackson/cs193p-developing-ios-11-apps-with-swift-4-lecture-1-notes-97731bd7862?source=rss-8df11fc7fc9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/97731bd7862</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[stanford]]></category>
            <category><![CDATA[cs193p]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Seab Jackson]]></dc:creator>
            <pubDate>Sat, 09 Dec 2017 07:17:38 GMT</pubDate>
            <atom:updated>2017-12-09T07:17:38.130Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[CS193P: Developing iOS Apps with Swift lecture 4 notes]]></title>
            <link>https://medium.com/@seabjackson/cs193p-developing-ios-apps-with-swift-lecture-4-notes-4646c91e3822?source=rss-8df11fc7fc9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4646c91e3822</guid>
            <category><![CDATA[stanford-ios]]></category>
            <category><![CDATA[paul-hegarty]]></category>
            <category><![CDATA[cs193p]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Seab Jackson]]></dc:creator>
            <pubDate>Sat, 01 Apr 2017 19:46:10 GMT</pubDate>
            <atom:updated>2017-04-01T19:46:10.405Z</atom:updated>
            <content:encoded><![CDATA[<h4>Views</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JjRVibgKjf_3Gwr8qiCPrg.png" /></figure><blockquote>Today we will be talking about custom views, specifically drawing views.</blockquote><p>What is a View?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eY8JDctQLZ7a3vNiX5wRig.png" /><figcaption>Apple Documentation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0VHt5TJglhDyHHPSCTOr0g.png" /></figure><ul><li>Basically we build our UI with these hierarchical rectangular views. Views can have many <strong>subviews</strong>, but just one <strong>superview</strong>. If you recall from the calculator app, our stack views had subviews of buttons, or even other stack views.</li><li>We can construct our views using interface builder in Xcode, or do so programmatically.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnW-FdyouTepRKWah_qi3g.png" /></figure><ul><li>There is an important property in UIViewController called <strong>view</strong>, which is the top level view in the window.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TK_04d1OOcJuhXrUd_s3Ww.png" /></figure><ul><li>Note that when this view rotates its <strong>bounds</strong> will change. We then have an opportunity to change all the subviews in this view. This feature allow us to specify the relationship of our views based on orientation or size of device.</li><li>Usually though we don’t need this view as we tend to add our views as outlets (@IBOutlet) which we can just work with directly.</li><li>So how do we initialize a UIView? Well if you recall initialization of a class has a lot of rules in Swift, so we try to avoid them as much as possible. However if we can’t avoid them there are two approaches to initializing a UIView that we should be aware of.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qkyHQ6clntId5hCqOpfI6Q.png" /></figure><pre>init(frame: CGRect)</pre><ul><li>The above initialization is used if we create the view programmatically. If we opt to create the views in Xcode using interface builder then we use this initialization:</li></ul><pre>init(coder: NSCoder)</pre><ul><li>What’s this coder about. Well all the views we create with interface builder gets <strong>coded</strong> into an XML file. When we run the program this XML file gets loaded in and contains basically the instructions for how to create these objects.</li><li>If we need an initializer for a view we need to implement both these methods so that our view can be initialized whether they were created in code or in using Xcode.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fa_SaaUZWWgE7brPKhXIjg.png" /></figure><ul><li>Another way to get our views set up which works only if they were created in interface builder is <strong>awakeFromNib</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ARyjlEKzR5PwpiEiYc_jhA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fiejZW8YTyWD7oVOHdSb_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8yCrmM2l-QRouT7PWYQcnA.png" /></figure><ul><li>Whenever we are dealing with anything that pertains to Drawing in our views, we use the type <strong>CGFloat</strong>. CG stands for <strong>Core Graphics.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gAVNa3-QTkUFk8YsJC1lHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8KgLvT-K1q2U0TLzFrGAEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AKfK5YerqnxlKMTd58FIPQ.png" /></figure><ul><li>CGRects have a ton of other convenience methods that we should do well to familiarize ourselves with.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PF4HYPifKrHGJqeYdPl0Ng.png" /></figure><ul><li>Let’s take a look at the coordinate space. We will see that it isn’t a cartesian coordinate system. In a cartesian system going up means increasing the value of the y coordinate. Here it is different.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sEFnu57ui4m4w3uOaeH2Ww.png" /><figcaption>Apple Documentation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AX89-U4EZaLFT6B_55vhDA.png" /></figure><ul><li>Note that we are dealing with <strong>points</strong>, and not <strong>pixels</strong>. Pixels are like the smallest possible piece of light that can be displayed on the screen. Some devices have a lot of pixels per point, meaning that the pixels are densely packed. This is great because it means that when we view curves such as fonts they won’t have jagged edges. Think Retina display of current macbooks and iPhones. Because of this difference in how many pixels are packed per point we can’t use pixels as the unit for drawing because on a densely packed pixel device, our drawing will appear very tiny, whilst on a lightly packed one, the drawing, or image will appear larger. Hence, we draw in points.</li></ul><blockquote><em>The most important property in all of UIView is </em><strong><em>bounds</em></strong><em>. Two other properties, </em><strong><em>center</em></strong><em>, and </em><strong><em>frame</em></strong><em> gets confused with bounds, but they have nothing to do with where we are drawing (bounds). Frame and center have to do with where we are in our superview.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VKxJ4M1HURAQJl9aMgd5_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qNHSLg1Q6OBYs3Bf-DT6xQ.png" /></figure><ul><li>Bottom line is to never use frame and center to draw. They should be only used to position you in your superview.</li><li>Since we don’t usually create views in code, how do we typically create them?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*va8iOleYI-7x4gWMw03s9w.png" /></figure><ul><li>Whenever we need to do custom drawing or handle some custom touch event then we need to create custom views.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hXQR8wm3Xp3-FJ-fZWNANg.png" /></figure><ul><li>The method <strong>draw</strong> is sent to us by the system when the system wants us to draw ourself. This is the only way we can draw in our view, in iOS.</li><li>This draw method takes a CGRect as an argument. This rect is some subarea in our bounds that the system wants us to draw. This is actually a performance enhancement because we can ignore it and draw the entire view by using its bounds. This can be a useful distinction because if draw is very expensive then we want to draw as little as possible.</li><li>We should never explicitly call draw(CGRect). If we ever need to do that then we should call one of the methods below:</li></ul><pre>setNeedsDisplay()<br>setNeedsDisplay(_ rect: CGRect)</pre><ul><li>Once we call one of the above functions the system, which knows best what time to draw, will implement draw(CGRect).</li><li>setNeedsDisplay(_ rect: CGRect) is also an optimization because its rect argument is what draw will use.</li><li>We will implement draw(CGRect) using <strong>paths</strong>. We then stroke, and fill these paths. We also use texts and images to draw, but lets focus on the paths for now. We’ll opt to using UIBezierPath which is a bit simpler for our drawing purposes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dSsDIkuJRjhojGY5ia_9kw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3CEHKY7JcumS86HjdVmpag.png" /><figcaption>Apple Documentation</figcaption></figure><ul><li>Let’s take a second to just understand the Core Graphics concepts.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ufPW6zkWOduad-XJRfguA.png" /></figure><ul><li>Stroking and Filling are the directives that will allow us to see the drawing on screen. If you think of a font, it really is just an exquisite path that is filled.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xy1teKOhUReOx6JfI8TJ7A.png" /></figure><blockquote>Let’s take on a real example of how we would use a UIBezierPath to draw a triangle on screen.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tRZiYCVVCnvB0_LT2PWEPQ.png" /></figure><ul><li>Note that none of the methods on the path such as <em>path.move(to: CGPoint)</em>, or <em>path.addLine(to: CGPoint) </em>will draw anything on screen.</li><li>To draw on the screen we need to stroke and fill, but for us to see anything we need to give them a color.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zRh6yeNTsMCu6mQvZVfp7Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mxVnsHIdTb_neXUi7lloTQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K2-DJTCPFyIQ74B5rrQIxQ.png" /></figure><ul><li>By default our views assume full opacity. so we need to set our view’s opaque property to false when we want transparency in our view. This is a performance enhancement because obviously some computing power has to go in to determining which pixels show through.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EzTXipalmLvYk7uTYfjLfg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sY4g0YAGNPpqOoxQlO2F6w.png" /></figure><ul><li>NSAttributedString is not a String in anyway. It is not even an NSString. NSString was that old Objective C style String that could be indexed through using Integers where as String in Swift is indexed by String.Index. So NSAttributedString is a “string” with characters that have attributes, like colors, fonts etc. We can then call draw(at: CGPoint) on the string or text and it will be drawn on screen. One key note about NSAttributedString that shows its age is that the var and let concept we use to distinguish between mutable and immutable in Swift don’t work with it. If we want to change it we need to specifically indicate that we want an NSMutableAttributedString.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hW9PQv1T16j5VtYtw_FcDQ.png" /><figcaption>Apple Documentation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H3k20PNCEUNzP9E8cYmWFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q-pjEonm3kddXAzfZdPbLQ.png" /></figure><ul><li>Fonts are super important in iOS, so how to we get them?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lETU8R172bJHKB8URtYNGw.png" /></figure><ul><li>Most of the times we would be setting these font attributes in Interface Builder.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8b5E0CRJFm1skgghO6i-Ng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WC3ROMINCJtq-DRLR-lBMQ.png" /></figure><ul><li>One thing to be careful about in UIView is that when a UIView changes size, it doesn’t ask you to redraw. When the bounds of a UIView changes it tends to take what we have drawn and try to stretch it to fit the new bounds. This as you might suspect, is not something that you typically want to happen. The option you might want is that if your bounds change, the system should as you to redraw within this new bounds. Fortunately, we can use contentMode to rectify this.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nynTXIoaNGmosQ-GVd4mLg.png" /></figure><blockquote><strong>Time for a demo!</strong></blockquote><ul><li>Create a new Xcode project called FaceIt.</li><li>Select <strong>AppDelegate.swift</strong>, <strong>Assets.xcassets</strong>, <strong>LaunchScreen.storyboard</strong>, and <strong>Info.plist</strong> together, then right click and choose <em>New Group from Selection</em>. Name that folder Supporting Files. We are doing this just so that we can focus on the more pertinent aspects of our app.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*XLt4L4VDM2RGTXupPDnt7Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*vPLuCk3qPk-zmJWjoNAMhg.png" /></figure><ul><li>When we select Main.storyboard we get an empty canvas that shows a view that displays nothing (just the white screen).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hBvRIxqgMl95cURIa3bceA.png" /></figure><ul><li>Click on ViewController, and delete the viewDidLoad, and didReceiveMemoryWarning methods.</li><li>Now we want to get started creating our custom view.</li><li>Click on File -&gt; New -&gt; File…</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dUfUK9UuJ_yJObJpnMrKDw.png" /></figure><ul><li>Last time when we created CalculatorBrain, we chose Swift File because it had nothing to do with UIKit, or the UI, and wasn&#39;t inheriting from any class. This time we will choose Cocoa Touch Class, and make our view a subclass of UIView. Give our View the descriptive name FaceView.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KXHPg4RC61s7Dl5Ff2LA6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NVL5Tv1aC-gxWjgjY-Ce8g.png" /></figure><ul><li>Right off the bat we see a commented draw function. It is commented for performance reasons because iOS doesn’t want to call draw on a view that isn’t doing anything yet. Since our FaceView will be drawing a Face let’s uncomment this method.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T26Wz5TmRTMVtjI7xXwY7w.png" /></figure><ul><li>Let’s go to storyboard to add a View to our ViewController. This is the custom View that we will use to draw our Face.</li><li>Scroll down the object library, choose View and drag it into the view of the device.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ykpx0G35niPRzCvyLMNhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UAv3lJq_H-svZg03q-sPSQ.png" /></figure><ul><li>Line up the View with the blue lines, and expand it each of its four edges to fit the entire size of the display. We want to tie this view to each of the four edges of our display.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A0p3q4LcI389AoD8wsPhYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*8RaK7Qjl8uNvu_mObaBsNA.png" /><figcaption>Fourth from right is the <strong>Resolve AutoLayout Issues </strong>button</figcaption></figure><ul><li>A nice easy feature that allows us to do that is if click the Resolve AutoLayout Issues button and selecting Reset to Suggested Constraints.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*cVW_eTUdSJByxwI5vuSA8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*HKr3hSFLzCjsLmIQJ9fjTg.png" /></figure><ul><li>One crucial thing about this View is that it is a <strong>UIView</strong>, and not a FaceView. So no matter what we put in our draw method, it will never be called. We need to click the Identity Inspector, and change the class name to FaceView.</li><li>Now we need to implement our draw method for this custom view.</li><li>Here’s the big idea! We are going to create an emoji face with a circle for a head, two smaller circles for eyes, and an arc for mouth.</li><li>Let’s start by drawing the head. We will be using UIBezierPaths, which gets the current context automatically for us so we don’t need to worry about getting <strong>UIGraphicsCurrentContext</strong>.</li><li>We want our head, or skull whether its in the landscape or portrait orientation to fully fit in the screen. Since the limiting factor would be the smallest dimension of the screen, we want our skull to be in line with the smaller of the two sides.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w4BYUxxYww-gDyrIgsqqhg.png" /></figure><ul><li>We divide by two because we are using the skull radius and not its diameter.</li><li>We want to make sure our skull is in the center. Can we do this?</li></ul><pre>let skullCenter = center</pre><ul><li>Although <strong>center</strong> gives us the center it is in a different coordinate system. We are in the <em>draw</em> method, so we need to be using the<em> Core Graphics</em> coordinate system where (0,0) is in the top left of the screen. We could convert center to this coordinate system.</li></ul><pre>let skullCenter = convert(center, from: superview)</pre><ul><li>An arguably better and more readable way of getting the center is to create a point that is the center.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*amw66Z_bbavW786RAXFI9g.png" /></figure><ul><li>Now that we have the center and the radius, we can use a UIBezierPath to draw an arc all the way around to make a circle.</li><li>The UIBezierPath constructor for an arc needs a start angle, and an end angle. Our start angle will be 0. For a full circle, the end angle will be 2π since this degrees is measured in radians.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*pRSLFba2J97oU4SCduFpLg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JvzqOih2QeNYGO8JXUyrVw.png" /></figure><ul><li>When we implemented that we get a warning.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*CtZvinD3EvDqreFqY7Z8dg.png" /></figure><ul><li>Well it is doing this because we are using UIBezierPath, to draw, and when we are drawing we need to use CGFloat. Swift cannot infer whether the 2 is an Int, or a Double. Fortunately, CGFloat has a static function for pi (π). Thus, we can use CGFloat.pi instead of Double.pi, and that should solve our issue.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hkXo4vdu_YTbeTtT-5w6nQ.png" /></figure><ul><li>Let’s add some attributes to our path.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zMuHHWNbjEmev6rDr9SbwA.png" /></figure><ul><li>Here we give the line a width, and use set() to set both the stroke color and the fill color to blue at the same time. We could have done that in two separate instances of using setFill(), and setStroke(). Finally we use path.stroke() to draw the arc.</li></ul><p><strong>Build and Run …</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*GOuYF2XDp3wpironXZ6Rlg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9hU3iMk0yK_4xDStse-VkQ.png" /></figure><ul><li>Woo hoo! We have a circle! However, it is being cut of at the sides since out line width is thick. Also, when we rotate our iPhone the circle becomes an oval. Let’s fix those issues.</li><li>Why does it turn into an oval. Well that has to do with the content mode. When the device rotates, and the bounds have changed. It is not redrawn, it just seems to be scaling the bits. To fix this, we go back into storyboard, select our view, and in the attributes inspector, we change Content Mode to <strong>Redraw</strong>. Our Content Mode was initially set to <strong>Scale to Fill, </strong>which is why it tried stretching the circle creating an oval<strong>.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eA71d8hUfvI4K4Up9DqjsQ.png" /></figure><ul><li>How about that edge problem, well let’s create a scale that’s say 90% or 0.9 then we can multiply our skullRadius by this scale and it should make the skull smaller. Note this scale should also be a CGFloat, since we are in <em>draw</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4qJd8DbJ-4Jy28QX7UwVhQ.png" /></figure><p><strong>Build and Run…</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*TEHqTfmACxygYC4BF8xIbA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AQXfxSsQ2KSJlfKsWn1BsQ.png" /></figure><ul><li>Both problems have been fixed as the circle is no longer stretched in landscape mode, and the circle scales properly within the dimensions of our screen.</li><li>Next we need to draw the eyes and the mouth. Let’s take a step back and think about our internal architecture. What would be nice is if we have private methods that give us the path for what we want to draw, and we just stroke those paths. For instance, let’s say we have a method called <em>pathForSkull, </em>it will return a UIBezierPath for the skull which we can then stroke<em>.</em></li></ul><pre>private func pathForSkull -&gt; UIBezierPath {</pre><pre>}</pre><ul><li>We can then have methods for getting us the eyes, and the mouth, and all we need to do is stroke these paths to get an emoji face drawn. The basic implementation will look like so:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mf9XbmD8oVgmpNQbzZL1lg.png" /></figure><ul><li>This will make our draw method much more compact. The skullRadius, and skullCenter are properties that we want things like our eyes and mouth to be relative to. That is, if our skull is small then our eyes should be smaller as well. We want to keep things in proportion. Since these are things that might need to be recalculated, we can take them our of draw, and make them private computed properties. That way, no matter if our bounds change, we will be able to recompute the proper values.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ezRpGHJj1ej9HaU2g1LdxA.png" /></figure><ul><li>Notice that in our computed properties for skullCenter, and skullRadius, we are not using <strong>get </strong>and <strong>set</strong>. We aren’t using set because we cannot set the skullRadius and skullCenter. If we are only getting then we don’t need to explicitly say get because it would be redundant. We just return whatever we are getting, and it is implicit for that to be the implementation of a get.</li><li>Let’s create the path for getting the eye. It is most certain that the path for both eyes will be the same so we can create a new type Eye as an enum to distinguish between the left and the right.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kn5iUzd9A31bHspyboFkdA.png" /></figure><ul><li>We do also need some constants to let us know where the eye, and the mouth are relative to the center. We can use a struct called ratios to store these ratios as constants, and put them at the bottom of our <em>draw</em> function.</li><li>These constants are: <br>- skullRadiusToEyeOffSet = 3<br>- skullRadiusToEyeRadius = 10<br>- skullRadiusToMouthWidth = 1<br>- skullRadiusToMouthHeight = 3<br>- skullRadiusToMouthOffset = 3</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AP5_cPY99HvRGaBgDr5ELw.png" /></figure><ul><li>So how are we going to use these constants in conjunction with the skullRadius and skullCenter to get the path for the eye?</li><li>First, we need to find the center of the eye, so we are going to write a function, let’s say <em>centerOfEye</em> that does that. Since we will only need this function for the eye we can just put it inside our <em>pathForEye</em> function.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xqz6qpbe3KdSo2mZbJ163Q.png" /></figure><ul><li>We initialize the eyeCenter to the skullCenter, and then use the offset to position it correctly. Since both eyes will have the same height position in the head that is easy to calculate. Notice that we minus the offset because that means up in the Core Graphics coordinate system.</li></ul><pre>eyeCenter.y -= eyeOffset</pre><ul><li>The x position of each eye has to be different. Since we are starting from the center then to reach the left eye, we must subtract by the offset from the center, and to get the right eye’s position we must add the offset to the center. Here we use the ternary operator to do just that. If we want to find the left eye’s center it gives us a value of -1, which we multiply to the eyeOffset to get the -eyeOffset, otherwise we get a positive eyeOffset. Basically we are starting with they eye in the center, and then moving up by some offset, and over (left or right) by some offset.</li><li>Now that we can get the center of the eye let’s get the eyeRadius, and we would be able to draw the eye using a UIBezierPath</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*STp4_ptTkBvIOrP41jT-fw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x3HDbndVBm2qy_azur0k3Q.png" /></figure><ul><li>This essentially gives us the path for the eye, so now we can go back to our draw function and just draw this path for each eye using the stroke method.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*F78P-KcrDOM-KWX2_R6l_Q.png" /></figure><p><strong>Build and Run…</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*Ii5aRVfVb0sEASIkHOZgjA.png" /></figure><ul><li>Looking good! We now have our head, and our eyes drawn all in nice proportion regarding size and relative distances apart.</li><li>What could be cool is if we had opened eyes and closed eyes!</li><li>Just like how we had a public property<em> scale</em> that the user can change we can create another public property, eyesO<em>pen</em>, that would be a bool. The pathForEye will look at this boolean property and give us the correct path for either the eyes closed, or the eyes opened.</li><li>We already have the path for if the eyes are opened, we just need a new one for if the eyes are closed. We can just create a path that is a horizontal line to depict that.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*w6g6j5dn4XgCyeHTnC75lA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EmJ6D85P-ddr9ZbJ_uETAw.png" /></figure><ul><li>Notice how we implemented the path for either eyes. Even though path is a constant, Swift is smart enough to know that this path is conditionally initialized. That is, its value is dependent on the <em>eyesOpen</em> property, and never changes once it is set. If <em>eyesOpen</em> is true, path has a value that is a circle depicting the eyes open, otherwise, path will draw a horizontal line. We place a point to the left of the eye’s center, and draw a line to a point to the right of the eye’s center.</li></ul><p><strong>Build and Run …</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*7ajNb4wgwmhKbDTM2oFYhg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*h_VmgXFw9MXXD0F9Fd0YzQ.png" /><figcaption>on the left: eyesOpen = false, on the right: eyesOpen = true</figcaption></figure><ul><li>Now that we have our eyes, the next thing on the agenda is our mouth. Like the others we will create a pathForMouth function, and stroke its return value to draw the mouth.</li><li>Let’s start by drawing the mouth as a rectangle just so that we can easily position it.</li><li>We can use the constants to help us get an idea of the mouth’s width, height, and offset. This offset would be the vertical distance from the middle of the face.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pzV9I6gLPjGWGC3vFxgBrg.png" /></figure><ul><li>We can now use the values to create the rectangle in which we are going to put the mouth.</li><li>We can use a CGRect to make this rectangle with the constructor:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MglIwmo_ooHzg11olnqOfA.png" /></figure><ul><li>The x, and y, values will be the origin of the rectangle, and the width, and height would be the mouthWidth, and mouthHeight respectively. The x position would be the center shifted half the mouth’s width to the left, and its y position would just be the skull’s center shifted down by the mouth’s vertical offset.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*F-7Kcsgq0bG_UJZRScy-6g.png" /></figure><ul><li>Once we have the mouthRect, we can use UIBezierPath to create the rectangle, and then return this path. Once we have the pathForMouth, we can just stroke it to draw it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ftb35eAAh_eZCVqtmR46sQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*le-xo4GeUAys_lQO-9iHKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*rUFvPuSHRoAO6_ljDpnbmg.png" /></figure><ul><li>Now that we have the mouth we need to think about how we can implement it as an <strong>Bezier Curve</strong> where concave upwards displays a smile. We can create a public variable, just like <em>scale</em> and <em>eyesOpen</em> called <em>mouthCurvature</em> that can determine the extent of the smile.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eEINp12kOJkT0zVzCUa-Pg.png" /></figure><ul><li>Note that we defined mouthCurvature as a Double, and not a CGFloat because it isn’t our drawing per se and more a concept, but we will need to convert it to a useful CGFloat for drawing purposes.</li><li>Let’s take a quick look at Bezier curves.</li></ul><p><a href="https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Computer_graphics">Bézier curve - Wikipedia</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*brOad2e1LJrW-RBHN023PQ.png" /></figure><ul><li>A Bezier curve is basically a line between two end points, but there are two other points called <strong>control points</strong>. You can think of it as though the control points are pulling on a line and making it a curve. We can think about our rectangular mouth and provide the start and end points as the mid point of the left and right edges of the rectangular mouth. We can then put our control points along the bottom edge, so as to create that concave upwards curve, or smile. If we put our control points at the top edge of the rectangle then we get a concave downwards curve to produce a frown.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HotNPvbRRWVFZUkcwDCKtg.png" /></figure><ul><li>We have now added the fixed start and end points for our bezier curve, which are situated in the middle of both left, and right edges of the rectangular mouth.</li><li>Now we need to think of our two control points. The further down we put them the greater the curvature, and the resulting smile. Out mouthCurvature property is therefore going to help here. We could now create that meaningful CGFloat property, let’s call it smileOffset, that takes the concept of mouthCurvature into consideration.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KrO9zr1JXUvPxBxXkdjaXw.png" /></figure><ul><li>When we try to multiply mouthCurvature by the height of the rectangle, we get a warning because mouthCurvature is a Double, and mouthRect.height is a CGFloat. We could just convert the Double to a CGFloat to fix that like so:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hAv0ft5OuNRr8W1vAyZJoA.png" /></figure><ul><li>One very important thing is that we have to be strict about the mouth curvature only being between -1, and 1 otherwise we might have a face with a smile all the way down to the floor!! Let’s enforce that.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXg3gt_TXILkHTafhjr1aw.png" /></figure><ul><li>Whatever value of mouthCurvature we get, we compare it to 1, and take the minimum (upperbound = 1), then we compare that minimum with -1, and take the maximum (lowerbound = -1). Thus, restricting our overall value to be between -1, and 1.</li><li>Now that we have the smileOffset, we can say how far down, or up our control points are. We will set the two control points cp1, and cp2 to be a third the distance from start and end respectively. How far down, or up they are (since mouthCurvature can be negative) is just the smileOffset.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aeFVqlTyKpnb-4toAk9nPQ.png" /></figure><ul><li>Let’s leave the rectangular face just for a second for reference sake and draw the curve, now that we have everything to complete the Bezier curve. All we need to do is move to the point which is the <em>start</em>, and add a curve that goes to the <em>end </em>with the corresponding <em>control point.</em></li></ul><p><strong>Build and Run…</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UsrcBv-OYpPBfDbpF30_rg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*BFjhBtOW-0IpqimNVqudGw.png" /></figure><ul><li>Nice! We don’t need the rectangular path anymore, so we could just delete the path that creates UIBezierPath(rect: mouthRect) and just create an empty UIBezierPath with UIBezierPath().</li><li>We should also make the lineWidth 5.0, let’s also change the mouth curvature to -0.5 which we expect should give us a slight frown.</li></ul><p><strong>Build and Run…</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O5Xw6OCGc1QqPs_61UHKKQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*V_l4LrshOOtij26tYlybyw.png" /></figure><ul><li>This is awesome! One pain though is that every time you change say, the scale, or the mouthCurvature, or eyesOpen, you have to always be building and running the application to see the effects. Wouldn’t it be cool if we could see this change in Interface Builder? Wouldn’t it be even more amazing if we can inspect these things in Interface Builder as well? The answer is we could absolutely do that!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OzXO5QwYb5bNt43CQT0f_Q.png" /></figure><ul><li>All we need to do is add @IBDesignable to the top of our View.</li><li>When we build and run this time, and look in our storyboard we see the results.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1KLu0Tf0cs6CHqEw4zAx3Q.png" /></figure><ul><li>Unfortuntely, if we look on the right at the attributes inspector, we don’t have an inspector that can inspect our properties.<strong> @IBInspectable</strong> comes to our rescue!</li><li>Let’s make scale, mouthCurvature, and eyesOpen all IBInspectable.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WUBENFP_XFQdCVlRiXNzAQ.png" /></figure><ul><li>We should also make the lineWidth IBInspectable, though we will have to make it a variable.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*9srEcn-QCppMZcl61P3CUA.png" /></figure><ul><li>We can now make all the parts of the code where we set the lineWidth = 5.0 to just be equal to lineWidth like so:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*SkLs8DwJYdzndXq7UoZ9qA.png" /></figure><ul><li>We can even make the color inspectable, by making a property, color, for it. We then change anywhere in our code we used color to use this color variable.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hCVARyRECZKeWJI6ntCKSA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*DYVNvI2UCHkAwexBi1LsjQ.png" /></figure><ul><li>If we go back to our storyboard, we should see that our properties are now inspectable as <em>scale</em>, <em>mouth curvature, line width</em>, and <em>color </em>are things we can change directly in Interface Builder.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H14Ck5-MFMKbDoZXGx4WFA.png" /></figure><ul><li>Notice that we are not seeing the eyes open property show up in the inspector. That is because we did not explicitly provide the type. Even though Swift has type inference, for our properties to be inspectable we must explicitly provide the type since Interface Builder cannot infer types.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*9wOp8Itrib6iR2T3VuiEGQ.png" /></figure><ul><li>Set the <em>scale</em> to <strong>0.9,</strong> <em>color</em> to <strong>orange</strong>, <em>mouth curvature</em> to <strong>0.5</strong>,<em> line width</em> to <strong>2 </strong>and <em>eyes open</em> to <strong>off</strong>. Interface Builder will use these as our settings such that when we run the app, we get the same results.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cOxWL-hJNvlsMfM6VuLwmA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*H2ds-CsZbFQiGIcG-2i2Kw.png" /></figure><blockquote>That’s it for today! Pretty cool stuff right? Next time we are going to add a Model to our MVC, add some gestures, and talk about multiple MVCs.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4646c91e3822" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CS193P: Developing Applications for iOS with Swift Lecture 3 Notes]]></title>
            <link>https://medium.com/@seabjackson/cs193p-developing-applications-for-ios-with-swift-lecture-3-notes-699fe8c4e730?source=rss-8df11fc7fc9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/699fe8c4e730</guid>
            <category><![CDATA[cs193p]]></category>
            <category><![CDATA[stanford]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Seab Jackson]]></dc:creator>
            <pubDate>Tue, 21 Mar 2017 23:43:18 GMT</pubDate>
            <atom:updated>2017-03-30T01:20:59.929Z</atom:updated>
            <content:encoded><![CDATA[<h4>MVC, iOS, Xcode and Swift Demonstration</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IRjK8I_6imu6ZcPm4u_5gA.png" /></figure><ul><li>This might be the only lecture where there won’t be a demo, and would rather be all slides.</li><li>The objective really is to now get up to speed on Swift.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IR7ZiG4x845qviOewe341Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8HYsHtIVKfkYzG8WIVYFFw.png" /></figure><ul><li>Note that an Optional is just an enum with two cases; <strong>none,</strong> which means <strong>Not Set</strong>, and<strong> some</strong>, which means <strong>Set</strong>. In the <strong>some</strong> case, we have an <em>associated value</em>.</li><li>The ? we use to represent Optionals are really just syntactic sugar to make our code look more readable than directly writing out a bunch of enums.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bZrFXccqtAep2qmx16kM6A.png" /></figure><ul><li>When we unwrap with the !, all we are doing is just switching on the various cases of the enum.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*5FBV3LnmED5o7AfgZuUYCA.png" /></figure><ul><li>To safely unwrap optionals we sometimes use the <strong>if-let</strong> pattern. Basically, it’s saying if we have a value then do something, but if their is no value, or the optional is not set then just ignore or break.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*JbTYKfRhkVislK6fN3S8Kw.png" /></figure><ul><li>An interesting feature of optionals is that they can be <strong>chained</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HJu71TT4c_vGWDm1-SnXhw.png" /></figure><ul><li>Note that since we want to get the value of an optional’s optional we need to do two<strong> if-lets</strong> to get that value. Instead of writing all this code we can use the ? in a special way to access the value of the optionals. The ? is essentially saying unwrap this optional if there is a value, but ignore the rest if the optional’s value is nil. As you can imagine, optional chaining allows our code to be succint. Too many if-lets can result in one is called the pyramid of doom.</li></ul><pre>if let temp1 = someValue1 {<br>    if let temp2 = someValue2 {<br>        if let temp3 = someValue3 {<br>            // do something<br>        }<br>    }<br>}</pre><ul><li>Another cool feature is <strong>Optional Defaulting.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47fuC7tYjcEm1aNpn_xxOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B9ar5AUjcsvbZ5eSuUKMUg.png" /></figure><ul><li>It is highly recommended that you give your tuple elements a name as it can provide great clarity in your code as to what the elements actually mean.</li><li>We can also use _ to ignore aspects of the tuple we are not interested in.</li><li>We can also use tuples as return values of a function.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EG4fg8rCZBD76ou3Ozd0JA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YB9KT9e9LdEe2UoxWcCBZg.png" /></figure><ul><li>Note that the implementation of Range has a <em>generic</em> type, since we can have a range of Ints, Floats, or String, for example. This generic type T, though, must be <strong>comparable</strong>. That’s because range needs to know that startIndex is less than endIndex.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*larDu80t0VCtlfnWQI6cNQ.png" /></figure><pre>1..&lt;10<br>// This is a range from 1 to 9 (10, the upper bound is excluded)</pre><pre>1...10<br>// This is a range from 1 to 10 </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bDSr-ujc8sq_-yE9YmRyzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jmhT5VokiyITR6YKe7dIzA.png" /></figure><ul><li>One very important point is that the <strong>subrange of a String is not a Range of Ints</strong>. We cannot use integers to iterate through Strings.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFITJLoqrjDYBsukSsbdLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iOiyATdW9sRHdIOZf0UO1g.png" /></figure><ul><li>Once the upper and lower bound are <em>stride-able</em> by Int then CountableRange creates a <strong>sequence. </strong>We can then iterate through this sequence.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3XjTCY7lAYjNeG8ukdL8xA.png" /></figure><ul><li>Arrays and Dictionaries are sequences, and is therefore enumeratable with a<strong> for in</strong> loop.</li><li>What if we wanted to iterate through Floats though?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g5iJ1l_vmWpTUPJ1atLDSA.png" /></figure><ul><li>Since a range of Floats is not a CountableRange, we cannot use the normal <strong>for in</strong> to iterate through them. We use the <strong>for in</strong> with <strong>stride</strong> to do so.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J6oMqlzebVwBom_Jzo8EOg.png" /></figure><ul><li>We have seen data structures like Classes, Structs, and Enums. There is also another data structure called <strong>Protocols</strong> that we will look into later in the course. One similarity between the data structures we have learned about so far is that there declarations are the same just that they have different keywords, and that with a class you can also specify its super class.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SQrWm6zzInanEScPiCIBeQ.png" /></figure><ul><li>Another similarity is that all our data structures can have methods, or functions on them as well as properties. <strong>Enums though, cannot have stored properties.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5LME3ZSrLh9B5Aqerd-nDw.png" /></figure><ul><li>They also share similar initializers though again enums have no initializers, since there value is already set for each case.</li></ul><p>What are their differences?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TWmifKv1n4XaLhlCmS8gCg.png" /></figure><ul><li>The most important distinction is that classes are reference types, but structs and enums are value types.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RlQysNHCruOxlNtERDQH9Q.png" /></figure><p><em>Most languages with object oriented programming capability use this pass by reference manner to work. There is a somewhat new frontier of way of programming with a case to be made called </em><strong><em>functional programming</em></strong><em>. It takes a different mindset, but basically it allows your code to be more easily testable because you use functions to say given this input, my program should have a predictable output. Swift is built with functional programming capability.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Stc7X7Px-JIBQJ4LJrc4bg.png" /></figure><ul><li>We see that the <strong>internal parameters</strong> are used in the implementation of the functionality of the method, but that the <strong>external parameters</strong> are used when calling the function.</li><li>We use _ as the external parameter when we want to ignore that parameter when calling the function. This is typically done 99% of the times for the first parameter, and it is always usually the case that we do this when it is evident from the function name that the first parameter might be redundant from a descriptive point of view.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Vp_k2yPT0DR74W1JFxGqg.png" /></figure><ul><li>If you want to change the original implementation of a class, or struct for example you indicate that in Swift using the <strong>override</strong> keyword.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-7qKHQMt8Wuylp9P4dF6gg.png" /></figure><ul><li>Types, like String, Double, and Int, can have methods or properties on them. We call these static methods as opposed to instance methods, which are methods on things of a particular type. For example pi is a static method on the type Double. That’s why we say Double.pi to get the value of pi as a Double. We use these static methods mainly as utility functions that won’t necessarily be able to act on an instance of the type, but on the type itself.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gDxif076cnTm8aDNnIeCPQ.png" /></figure><ul><li><strong>Property observers </strong>are pieces of code that gets executed when the property changes. You can find out just before the property changes, or just after it does change. A simple example of how these can be useful is let’s say we want a button to change based on the color of a background then we can set up a property observer to execute changes in the button based on whether the background color changed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UydaXbCRx9-9EZvp62hdZw.png" /></figure><ul><li>Why would something want to be a lazy property. This can best be explained by an example. What if our calculator brain was very expensive resources wise to create. We wouldn’t want to perform such operations unless at the point when the user is specifically requesting us to use that service. Basically we use lazy here to delay expensive operations.</li><li>Another reason to have a lazy property is because it allows us to get around the loophole in Swift that all properties must be initialized before we can use them. Not only that, they also have to be all initialized before we can even send a method to that class, or struct etc. That means we can’t invoke any of our own methods until we are fully initialized.</li><li>What happens then if one of the requirements we need to initialize needs to call a method on ourself. That’s an odd situation to be in. If we need to initialize something to be allowed to call ourself, but we need to first call ourself before we can initialize something then we are in a deadlock. Luckily lazy properties allow us to do just that because being a lazy property counts as though that property is initialized.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fioTjhfluTt93ZmUpulTYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*27aaD0Q8BV8eNB5mI2eYzw.png" /></figure><ul><li><strong>Filter</strong> is just a method on array. It has an argument, <em>includeElement</em>, which is a function. This function takes elements of the same type as in the array and returns true. The filter method then returns elements of the same type as in the original array who’s boolean value from applying the function <em>includeElement</em> is true. In the example above, we pass to filter a closure. Since Swift can infer the types we don’t need to say the types, or even return. Our closure is applied to each element in the array. We check to see if that element is greater than 20, if it is then it will be part of the array we will be returning. If not, then we just ignore that value. Imagine having to do this without a closure. We would have had to create for loops, with new arrays and our code would be much more verbose. Here with just this one line of code, it is so much readable. We are basically just saying, let big numbers be the set of numbers I filtered from my original array that are greater than 20.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p9Z4ekMjszERC-cEwvfAyg.png" /></figure><ul><li><strong>Map</strong> allows us to transform our original away to a new one by some mapping relationship with original elements of the array as input. In the example above we wanted to transform the integers to strings. The function <strong>map</strong> has an argument <em>transform</em> that is a closure. This closure transform the original elements into new elements. The map function then returns an array of these new elements.</li><li>Note also how our closure in map is slightly different than our closure for filter with regards to parentheses.</li></ul><pre>map { }</pre><pre>filter({ })</pre><ul><li>If the closure is the last argument to our function, or that our function only has one argument, we can use <strong>trailing closure syntax</strong> where we ignore the parantheses.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eFh9pkBbW9BmJ1i96i3hLA.png" /></figure><ul><li><strong>reduce</strong> is a closure with two arguments. It takes the <em>initial</em> value in the array, and <em>combine</em>, which is the value so far. For instance, in the example above. We start with an initial value of 0, and we combine with a relationship to get a solution, by adding each element of the array to our value so far. Once we get to the end of our array we will return the value we had so far, which in this case would be the sum of all the elements.</li><li>Note also that we can just use +, since in Swift + is an actual function that takes two arguments and produces the result of a summation of those arguments.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AQTierxnwYKubHKya9S1oA.png" /></figure><ul><li>We can use square bracket syntax to access items in our dictionary. However, we will always get back an optional because the value could be nil. Our item could be there, and there is a possibility we don’t have that item.</li><li>If we want to add items to our array we must make sure that it was declared to be <strong>mutable</strong> with the <strong>var</strong> keyword and not <strong>immutable</strong> with <strong>let</strong>.</li></ul><pre>pac12teamRankings[&quot;Cal&quot;] = 12</pre><ul><li>This code is saying for the key, Cal, in our dictionary pac12teamRankings save the value 12.</li><li>Since dictionary is a collection, which can be <em>sequenced</em> we can use <strong>for in </strong>to iterate through our dictionary, and since a dictionary is a set of key value pairs, we can use a tuple: (key, value) to keep track of the keys and values as we iterate through the dictionary.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RRlDzOz4YeUOhC3l6IHoig.png" /></figure><ul><li>In most languages, Strings are just a collection of characters. Since Strings in Swift are represented as unicodes, we need another abstraction that can count the characters in a String the way a human would. Thus, we have the notion of a <strong>Character</strong> in Swift. Getting the characters by using these String.Index though is quite tedious.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TqXyPJhUZNrQzZGKX1Vhgg.png" /></figure><ul><li>Since String is not a collection of characters, and thus not a sequence, we cannot use for-in to iterate through it. However the property <strong>characters</strong> on a String returns a collection of characters, which we can then iterate through.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UVUi2iGmHHFxbrjbJuUdfg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nucmd0k4jZIgunm6rVcYdw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2HnsYNy3PGiSIUBqwf5jRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aZFaaeEjnbAb1TzmZNRWng.png" /></figure><ul><li>Initialization is more complex for classes that are not base classes. With structs you get a free initializers.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9gekyao-wI9tMDy-egLb7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z-56WKJey4tKEsmyHSQfjA.png" /></figure><ul><li>The complications in initializations arises when we start thinking about classes and inheritance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hFXm_NRkP3vPPqHj7FJvtA.png" /></figure><ul><li>Designated initializers are just the default initializers. There is no keyword designated.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CR7uujav1Q5XQcEicuEWhw.png" /></figure><ul><li>There are many rules, but we will deal with them as we progress throughout the course.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SViyVW2MBKKvze-Np22u1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UyAXzelBaskZom9jbKfBcg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VAcNTICb2hujVIzRPxkN9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hQfLrLPUR8CTtHcsYqKYAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j_TLnvOgZcyXw15YmeDEBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SnJIOGGRCdUcwIPDP8PODQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EtKSLlu5q334fomy_71_Ag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F44NyWiOoomi33EV4csUqw.png" /></figure><p><em>That’s it for this lecture! A lot of slides, but we will review the concepts as we proceed throughout the course.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=699fe8c4e730" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CS193P: Developing Applications for iOS with Swift Lecture 2 Notes]]></title>
            <link>https://medium.com/@seabjackson/cs193p-developing-applications-for-ios-with-swift-lecture-2-notes-14dd5d7c2e00?source=rss-8df11fc7fc9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/14dd5d7c2e00</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[paul-hegarty]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[stanford]]></category>
            <category><![CDATA[cs193p]]></category>
            <dc:creator><![CDATA[Seab Jackson]]></dc:creator>
            <pubDate>Mon, 06 Mar 2017 05:37:53 GMT</pubDate>
            <atom:updated>2017-03-06T05:37:53.795Z</atom:updated>
            <content:encoded><![CDATA[<h4>MVC, Calculator Demo continued…</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3lWKPsp07DpxLYbyQg_-Qg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jfqXblxpDTUvB2IuQ3762A.png" /></figure><p>What is MVC?</p><ul><li>MVC is basically away for us to divide up our apps into 3 different camps, namely the <strong>Model, View</strong>, and the <strong>Controller</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9232afW4ikbic5Pgo_5MWw.png" /></figure><ul><li>The <strong>Model</strong> has to do with what your application does. It has nothing to do with how the app is displayed, or drawn on screen.</li><li>For a Calculator app, the <strong>Model </strong>will probably be the part that does the calculating.</li><li>The <strong>Controller</strong> has to do with how the <strong>Model</strong> is displayed, or presented on screen (UI Logic).</li><li>The <strong>Views</strong> are your <strong>Controller</strong>’s minions. These are the things the <strong>Controller</strong> is going to use to put things on the screen like buttons, labels, tables, etc. to display what is in the <strong>Model</strong>, and to get input from the user to update the <strong>Model.</strong></li></ul><blockquote>It’s one thing to know how to divide your code into these three camps, but a crucial piece of the puzzle is the communication between them. That is, what’s allowed, and not allowed.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N71rdpbrT9pbcQaeGVvmsg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J04uMLOTuH4RlAnNK6Ef3Q.png" /></figure><ul><li>The <strong>Controller</strong> must be in complete control of the <strong>Model</strong>, and can talk to it anytime it wants. It needs total access because its job really is to present what is in this Model to the user, and to update the model based on user input.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s6UaP60gD5LKrRLpnnDbVw.png" /></figure><ul><li>The <strong>Controller</strong> needs to be able to use its minions however it wants to display the <strong>Model</strong>.</li><li>Most of the time the connection between the <strong>Controller</strong> and the <strong>View</strong> is via an <em>Outlet</em>. In Xcode this shows up as an <strong>@IBOutlet</strong>. For example, the <em>label</em> we used for the <em>display</em> in the calculator was an outlet that the <strong>Controller</strong> used to display numbers and results of calculations performed in the <strong>Model</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PSJLBab0DlQnlVQNIgavJg.png" /></figure><ul><li>The <strong>Model</strong> is UI independent, and the <strong>View</strong> is completely UI. They should absolutely never talk to each other.</li></ul><blockquote>Can the View talk to the Controller? Yes… and No….</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1MOfPyCWn3DUuBYQfmfIrw.png" /></figure><ul><li>The problem with the <strong>View</strong> is that all the minions in there are generic objects like <em>UIButton</em> and <em>UILabel</em>. These were created by Apple years ago, and know absolutely nothing about the app you are building (in this case a calculator). However, sometimes changes in the UI need to be communicated to the <strong>Controller</strong>. The way the <strong>View</strong> communicates with the <strong>Controller</strong> then has to be “blind”, and “structured”.</li><li>The communication is <em>blind </em>in that the objects in the <strong>View</strong> don’t know what classes they are talking to. For example, buttons don’t know anything about CalculatorViewController.</li><li>The communication is structured because since there is no knowledge of the objects on either end they have to communicate in a well defined, predefined way.</li></ul><blockquote>What are some of the structured ways that the View can talk to the Controller?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*doMEhFRBzbTMijoi1gjtCw.png" /></figure><ul><li>Target-Action: This is very simple as the <strong>Controller</strong> can hang a target on itself by defining a method, ie. an @IBAction. The <strong>View</strong> then calls this method when it wants to talk to the <strong>Controller. </strong>We used this <strong>Target: Action </strong>way of communication in our calculator app when we made the touchDigit function because we wanted a press on the button to invoke a method in our calculator and tell us which button was pressed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LU8_raTUQ7eyjcU_ChFJiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pyTS1vzrDGAakK_0B79sLw.png" /></figure><p>Sometimes the <strong>View</strong> needs to communicate something a bit more complex than “I was touched”. For example, a ScrollView, which is a generic <strong>View</strong> minion might need to tell the <strong>Controller</strong> that someone started scrolling, or indicate that a person zoomed in to a specific zoom scale. That is, it wants to notify the <strong>Controller</strong> because the <strong>Controller</strong> may want to react to that. Perhaps the <strong>Model</strong> is changed when you zoom in or out. Furthermore, maybe the ScrollView needs to ensure whether it is ok to do something. It may need to ask the <strong>Controller</strong> the question: “<strong>Should </strong>I allow vertical scrolling right now?”. We have a lot of messages that involves words like <em>Should</em>, <em>Will</em>, and<em> Did </em>that the minions want to ask the Controller. This form of communication is done via what we call a <strong>delegate</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NrbEWbRjFQAlXfxTAbNCLw.png" /></figure><ul><li>Delegate is an apt term here because the <strong>View’s</strong> minions are basically delegating some particular responsibility to the <strong>Controller</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GiyRDq-4k5Wmh-pDT2x1mw.png" /></figure><ul><li>The <strong>protocol </strong>doesn’t really know about the class, but it is ensuring that whatever we are communicating with will respond to a specific set of methods or properties. The controller then signs up to listen for these methods. We’ll learn more about this delegate pattern, so not to worry if it is a tad confusing right now.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YnrlRA12jaHMHyqQ8fO04g.png" /></figure><ul><li>There is a special type of communication that exists between the Views and the Controllers because the Views cannot, and should not own the data they display. For instance, let’s say we have an iPod Touch with thousands of songs on it. Should we make the generic tableView which basically just shows my data in a list be the owner of all my music? That would be insane especially from a performance stand point, not to mention synchronizing issues. So if Views can’t own the data, what do we do?</li><li>Well the View is basically going to use another protocol, called a dataSource, but this time with a different set of questions than should, will, and did. It will ask questions like: How many items are in this data? Give me the item at this location, or index etc. So every time, say a tableView wants data, it asks the Controller, which in turn almost alway turns around and ask the Model. This makes for some nice optimizations. Since the tableView can only show about say 10 data items given the confines of our screen, it only asks for 10, out of the thousands of music on our phone. Then as we scroll, it keeps asking for more data, only keeping the ones that is currently in the display.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GDpiYysII6xWN4aUbCraCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sCqJAaRQCNbACpC5Z0PriQ.png" /></figure><p>What about the Model communicating with the Controller?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HnDFFg-O0MAd7r4LagaaZg.png" /></figure><ul><li>So the model can’t communicate directly to our Controller, but what happens if there is a change in the Model, wouldn’t we want to update the Controller, so that this change can be reflected in the View. For example, let’s say I deleted one of the songs in my Model, then the Controller should know so that that song isn’t displayed in say a tableView.</li><li>Well the mechanism in how we set this up is to create that behaves kind of like a radio station. It then broadcasts things like ‘hey something about me changed!.’ The Controller then tunes it to this radio station, and when it hears a broadcast, asks the Model what changed since Controller to Model communication is a nice green line.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OMYPx7oXli-zo4vgdMatxw.png" /></figure><ul><li>Now, when we build our app, we aren’t just building one giant MVC. We can have a series of MVCs all communicating with each other, with each other MVC connected via a View.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1MSxi_VWhjnsJfid55U8qA.png" /></figure><ul><li>For example let’s say we are building a Calendar app.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jKxrPu5EvgJebfuVxwoJAw.png" /></figure><ul><li>Each of these different Views are three different MVCs, but their Views are connected to each other such that the Year MVC, is connected to the Month MVC, which is connected to the Day MVC.</li><li>Note that it is perfectly fine for different MVCs to share the same Model, and for Models to communicate with other Models.</li></ul><p>What we don’t want is this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ik2LSp9jjns1pqraJkJHSA.png" /></figure><p>That wraps it up for MVCs for now. Let’s dive back into creating our Calculator app so that it fits, or conforms to this MVC design paradigm that we just learned about.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zYUp7Ee76Thd-jOsY_g0HA.png" /></figure><ul><li>Recall where we left off from our calculator, it was performing the operations or calculations in our Controller. Since these operations have nothing to do with the UI, we should put these type of functionality in our Model class. Create a new Swift file, and call it CalculatorBrain.</li></ul><pre>import Foundation</pre><ul><li>Since this is going to be our Model Class, we import Foundation, and not UIKit.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*5vO3u9w8kDxpOfo-V5NiFA.png" /></figure><ul><li>If we look in our navigator we see that we have a <strong>Model: </strong>CalculatorBrain<strong>, View: </strong>Main.storyboard<strong>, </strong>and<strong> Controller:</strong> ViewController.</li><li>Now we need to think about our Model, and what its public <strong>API</strong> is. API stands for <strong>Application Programming Interface</strong>. An API is a set of subroutines, definitions, protocols, and tools for building application software.</li></ul><p><a href="https://en.wikipedia.org/wiki/Application_programming_interface">Application programming interface</a></p><ul><li>So we need to think carefully about what our model allows other people, like Controllers, to do.</li><li>We could opt to create a class, but lets opt to use a struct data structure as the model for our calculator.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*bbd7VnQvz6zozxvlrNXocA.png" /></figure><ul><li>In Swift, Structs are a lot more powerful than in other languages. In fact most of the data structures we have seen so far like <strong>String</strong>, <strong>Double, Array, Dictionary </strong>etc. are under the hood implemented as Structs.</li><li>There are two main differences between a struct and a class in Swift. Classes have inheritance, whilst structs do not. Thus, if you’re building an object that might need to be subclasses to be extensible, then you probably want to make it a class. The other difference is that classes live in the heap, and we have pointers to them. Structs do not live in the heap, and they are passed around by copying them. That is, classes are passed by reference, and structs are passed by value. This is a significant difference.</li><li>One might think that since these are passed by value that it will be highly inefficient to be copying them around, but the Swift compiler optimizes for this, and these value types are basically <strong>copy-on-write</strong>.</li></ul><p><a href="https://en.wikipedia.org/wiki/Copy-on-write">Copy-on-write - Wikipedia</a></p><ul><li>So back to that question about what our public API does. We know that somehow we will need to perform the operation, or calculations, so we’ll have a function for that.</li></ul><pre>func performOperation(_ symbol: String) {</pre><pre>}</pre><ul><li>We will let some mathematical symbol be the operation we are performing.</li><li>Now if we’re performing operations, we must need operands to perform on, so we’ll need another function that sets the operand. Let’s have our entire calculator work with Doubles, so let the the operands be of type Double.</li></ul><pre>func setOperand(_ operand: Double) {</pre><pre>} </pre><ul><li>Note that we use _ as our external parameter because we do not want when we call this function that it’s like this:</li></ul><pre>setOperand(operand: 5.0)</pre><p>It makes more sense for us to call it like so</p><pre>setOperand(5.0)</pre><ul><li>The former is rather verbose, but from the latter reads more succinctly, and its very evident from the name of the function that 5.0 is our operand.</li><li>Thinking about it, we will also need to get the result of these operations. In Swift like manner, lets create a computed property to get us that result.</li></ul><pre>var result: Double {</pre><pre>}</pre><ul><li>One think we need to be concerned with though is that we don’t want anything else to be setting our result. How do we make this read only? Well, just like currentTitle, on a button we can just make it <strong>get</strong>.</li></ul><pre>var result: Double {<br>    get {<br>    <br>    }<br>}</pre><ul><li>If we think about the internals of our calculator, we know that a calculator accumulates its answer as it’s calculating, so let’s create a variable that captures this running result. Other people should not be able to access this property so make it private.</li></ul><pre>private var accumulator: Double</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*xzcGuWLpGh8empcXXEZfNA.png" /></figure><ul><li>Notice that even though we haven’t initialized our variables we don’t get that no initializers error message like we had for classes. That is because Structs automatically get an initializer that will initialized all their uninitialized variables.</li><li>Let’s think about that accumulator for a bit. When the user first starts up the calculator, the accumulator would be in the Not Set state, so it makes sense to make it an optional Double.</li></ul><pre>private var accumulator: Double?</pre><ul><li>If we have this internal accumulator, how can we use that to implement our functions?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yXPpsMsUrcgOLXzVZYJ_zw.png" /></figure><ul><li>setOperand basically just sets the accumulator to the operand because when you set a new operand that just replaces whatever was in our accumulator. To get the result, we just return the accumulator. We do have some errors though. It is saying that ‘self’, meaning our CalculatorBrain is immutable, and asks us to fix it by adding <strong>mutating</strong> to the beginning of the function.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*iVhwyxAETzhpUaH0aD4-ig.png" /></figure><ul><li>This brings up another difference between Structs and Classes. Whenever we have a method that changes the value of the struct itself, we have to mark that method as mutating.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*9dNuj3X7yytv2oztqDw79Q.png" /></figure><ul><li>We do have another error. That’s because result is a Double, and accumulator is an Optional. Should we just unwrap this like so then?</li></ul><pre>return accumulator!</pre><ul><li>Absolutely not! There are going to be many instances when our accumulator will be in the not set state, and unwrapping a Not Set Optional will crash our program. When the calculator first starts up the accumulator will be in the Not Set state. Also, when we are performing an operation say, 5 * 3, the accumulator will remain unset as we enter 5 * until we hit 3, and then it’s Set, and provides the result.</li><li>We should also make result an Optional because if someone asks for an answer before we can evaluate the operation, we should just not return a result. For instance, if the user asks for 5 * then we can’t provide them a result.</li></ul><pre>var result: Double? {<br>    get {<br>        return accumulator<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TjD5vTrrILqESnShWdcjEA.png" /><figcaption>Model: Left, and Controller: Right on the screen at the same time.</figcaption></figure><ul><li>Let’s use the public API that we created to handle what we previously implemented in the Controller. We see that we don’t need to change touchDigit, or displayValue because those behaviors are mostly things that have to do with the UI. That’s one of the cool perks of doing MVC. Our UI is independent of our Model, or vice versa. We do need to take out performOperation though.</li><li>Let’s rewire this @IBAction performOperation method to use our Model to perform the operation. Ok so if we are to perform an operation, we know that if the user is in the middle of typing a number we need to set that number as an operand.</li></ul><pre>if userIsInTheMiddleOfTyping {<br>    // set operand<br>}</pre><ul><li>Since setting the operand is something my model should do. How do I communicate with the CalculatorBrain from the Controller? Let’s create a calculator brain for our Controller. It will be private because we don’t want anyone else coming in and messing with this controller’s calculator brain.</li></ul><pre> private var brain: CalculatorBrain = CalculatorBrain()</pre><ul><li>Since Swift can infer the type for brain, we can just use the more succinct…</li></ul><pre>private var brain = CalculatorBrain()</pre><ul><li>Now that our controller can talk to our Model, we can now set the operand, which would be the displayValue. Once we set the operand, we are no longer in the middle of typing.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*C0Amh_IkVOT1DT5ct_Kuxw.png" /></figure><ul><li>So now when we get the mathematical symbol from the button pressed we will just ask our brain (Model/API) to perform the operation with that symbol.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*GjVh3mH9Omka3sN_Mn35xQ.png" /></figure><ul><li>So when we click the button to perform an operation the Controller responds to the click via target-action, and is saying hold a minute now, I’m a UI guy. I don’t know anything about how to perform an operation. You know what let me ask my Model!</li><li>Once the operation is done, there is one more thing for us to do. That is, we need to set our displayValue to our brain’s result.</li></ul><pre>displayValue = brain.result</pre><ul><li>We can’t just write the above code though because result is an Optional. Let’s unwrap it the safe way using<strong> if let.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*HpURImUrjUVLLFtb4ab__Q.png" /></figure><ul><li>Now we have completely taken all the calculations of our calculator out of our Controller. This means that we can now focus our attention on building a very powerful Model.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*4JiHAgUGeclVeDdgcYan3Q.png" /></figure><ul><li>Let’s fix this implementation of performOperation that we copied over into our Model. Well we need to change mathematicalSymbol to symbol since the internal argument is symbol. Since we are now in the Model, and not in the UI, we don’t have displayValue, so let’s just set those values to the accumulator.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*Pjr7a2BuxNIDOI-9FxIfxQ.png" /></figure><ul><li>We still have some issues here because accumulator is an Optional. We cannot find the square root of an Optional. We could first safely unwrap the accumulator before we find its square root value with an if-let.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*rIPhRTSculjM86SzjpO9_A.png" /></figure><ul><li>Hmm we still have some error messages, what might those be? Well, remember our CalculatorBrain is implemented as a Struct, which is a value type. In this performOperation method, we are changing our Struct, so we need to mark this method as <strong>mutating</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*sczm_8uZqLCG4wEnjZIAcw.png" /></figure><p>We now have an MVC version of our calculator.<strong> Build and Run …</strong></p><blockquote>Our calculator still works! Now we will use some cool Swift features that we might not see in other languages to make our calculator a lot more extensible. Right now, if we want to add more operations to our calculator we will have to do a ton of different switch cases, then we might have to unwrap their values with if-let, and that’s just for unary operations. Imagine when we need to add binary operations. Thus, we need to build an engine that can easily deal with constants like π, unary operations like √, and binary operations like +.</blockquote><ul><li>Delete everything in the performOperation method because it’d be a mess if we continue like that.</li><li>Let’s think about making our calculator more extensible starting with constants. Wouldn’t it be cool if we had, say a table with the constants and their corresponding values, like so:</li></ul><pre>[ &quot;π&quot;: Double.pi,<br>  &quot;e&quot;: M_E<br>]</pre><ul><li>That way when we want the value of a constant, we just look it up in our table. How do we create a table in Swift? We use a Struct called a <strong>dictionary</strong>. Let’s create this dictionary and call it operations. Dictionaries in Swift can have a generic type, so it can be any type as long as the key, that we use is <strong>hashable.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*3UJQaA3dOL2eNBe7DIEMdQ.png" /></figure><ul><li>So now in our performOperation method, we just retrieve from our dictionary the value of the symbol sent to us.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*G8vp33STcmoR70GN3WxD4g.png" /></figure><ul><li>Why do we need to use an if-let when getting the value from a dictionary? That’s because maybe what we are looking for might not be in the dictionary, and so it’s value will be an Optional with a value of nil.</li><li>When we build and run, we see that the only constant we now support, π, works! This is now more extensible at least for constants that the implementation we previously had. It’s pretty weak that we can only do this for constants only though, wouldn’t it be cool if our table can look like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B8SNWZgQjLoYFF_fhk0Opg.png" /></figure><ul><li>This way it wouldn’t just work for constants. However, we have a challenge. Our dictionary’s value for a key must be a Double, but what is the type of square root? It’s really a function if you think about it. So we need to create a dictionary with mixed types in it. Let’s create that type using an enum. An enum in most languages is usually just a simple data structure with discrete values. In Swift, enums are more powerful than other languages as we’ll soon see. Let’s make our case just deal with constants and unary operations for now.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*0Kjz-_DY-VRND0IoCfuCpw.png" /></figure><ul><li>Once we have defined our type we can now let our dictionary work with this type instead of a Double.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2tvkVEVhV8rln6u9eg3h7w.png" /></figure><ul><li>Note that our dictionary type is now &lt;String, Operation&gt;, and not &lt;String, Double&gt; like previously. We use dot syntax to access the different cases of our type. π is a constant so we do Operation.constant. Square Root is a unary operation so it’s type is Operation.unaryOperation</li><li>Let’s change our performOperation to this for now:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*SNjU1olE3V9-Wgc1rFXwuA.png" /></figure><ul><li>We no longer save the retrieval of the value in our dictionary in a constant variable because now we will get back an operation which could be either a constant, or a unary operation.</li><li>In creating this dictionary with the new types though we have actually lost the fundamental meaning of the operations. We know that π is a constant, but we have no way of getting its value.</li><li>Let’s think back to how Optionals are defined in Swift. An Optional is basically an enum with two states: Not Set, in which case the value is none or nil, and a Set Case in which the value is Some.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*hzLBB9Wq_eZGmShJXHiMYA.png" /></figure><p>In the <em>some </em>case we have an <strong>associated value</strong>. This associated value isn’t unique to Optionals. It is a behavior that we can apply to all enums. So what we can do is that when we define our types, we can give them an associated value. To relate this to our dictionary, we can just provide the associated value of that operation. In the case for a constant, the associated value will be a Double.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*1T3FCTdPS_yHJteVU4TjAA.png" /><figcaption>constant has an associated value of Double</figcaption></figure><ul><li>The corresponding change in our dictionary for constant case would look like this.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P3e3pM3QXIA03_i6l2AeJQ.png" /></figure><ul><li>Notice that the associated value we give for the constant value, π, is the value of π as a Double (Double.pi). M_E is the Double value of the constant<strong> e</strong>. We’ll deal with unaryOperators and even binaryOperations a bit later.</li><li>Once we have the operation to perform how do we get the associated value out. We can switch on the varying operations to see if it is a constant, or unaryOperation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*S49nd4ERFElPn41SU8BH0g.png" /></figure><ul><li>As can be seen where the Double is higlighted for a constant, that’s basically saying, hey I want to help you get your associated value out. So how do we get that value out? We could create a variable there that captures that value, like so:</li></ul><pre>case .constant(let value):</pre><ul><li>This variable <strong>value</strong> will have the associated value, so we can then set the accumulator to that value.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*KJk_KyiwGRUXaHmYdNRg3A.png" /></figure><ul><li>Swift cases don’t fall through to the next case so we don’t need the break statements in each case. In addition, we do not need a default case in this enum since we have exhausted the two possible states that an operation can currently be.</li><li>Let’s try to tackle unaryOperations. This might be a bit tougher. What we would really love is this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HhdjuMF3KMBL2iLkjHARMQ.png" /></figure><p>That is, set our associated value as a function. Can we do that in Swift? Of course! One of the cool aspects of Swift is that functions are first class citizens. They are like normal types, just like Double, String, Struct, or whatever.</p><ul><li>How do we make our associated value be a function like square root or cosine. We those functions take a Double as input and produces a Double as output. Essentially the function signature should look like this</li></ul><pre>(Double) -&gt; Double</pre><ul><li>All we do is add this as the associated value for our enum’s unary operations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*sm8hYcxlePz5Jg-SGOn7aQ.png" /></figure><ul><li>Let’s play around with this type functions business for a bit in an Xcode playground.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8FrIJaSuKIJ_VaWXgUNrsA.png" /></figure><ul><li>We create a variable, f, that has the type (Double) -&gt; Double. The sqrt function has the same type, so we can make f equal sqrt. Now we can call f(81), and since f is equal to square root, we get 9. We can even let f = cos, since cosine is a function that takes a Double and returns a Double.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mJNJVQFuUjOW6OwFeIoCjg.png" /><figcaption>we see cosine of π/3 (60 degrees) is 0.5</figcaption></figure><ul><li>We can even create our own function. Let’s write a function changeSign that just changes the sign of a value. Since changeSign has the type (Double) -&gt; Double we can set f to changeSign, and when we do we get the value of 0ur input, 81, changed to -81.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITuiCxYHHfQLvDdTpS2vVw.png" /></figure><ul><li>Let’s even use this function we just wrote changeSign and add it to our calculator. Place it at the top of the file as a global function.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*pAeUHVelMDepvzLYehx4Mg.png" /></figure><ul><li>We copy and paste any operation button since it is already hooked up to performOperation. Our new button will now share that same IBAction, or method. Change the title of the button to plus or minus. You can find these different symbols clicking the edit menu, and then <strong>Emoji &amp; Symbols</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*epKeqH7-V5I8q67aWvlBuA.png" /></figure><ul><li>Also, add the ± operation to our operations dictionary. It is a unary operation, and the method that corresponds to this operation is the changeSign method we wrote, as a global function.</li><li>Let’s go back to our performOperation method. Remember how in the case of a constant, we were able to get the associated value, like this:</li></ul><pre>case .constant(let value):</pre><p>We can also get the associated function for a unary operation like so:</p><pre>case .unaryOperation(let function):</pre><ul><li>Note that you can name the variables to get grab the associated values almost anything you want, though, value, and function seem like very apt names.</li><li>We then call this function on our accumulator, and that will be the new value of our accumulator. Currently, we are doing this:</li></ul><pre>accumulator = function(accumulator!)</pre><ul><li>We should safely check whether our accumulator is nil though. We could use an if-let, but another way to safely unwrap our Optionals is just simply check that the Optional isn’t nil.</li><li>Our calculator now works perfectly fine for constants and unary operations. We should try tackling binary operations now. This is a bit more challenging as we are really doing two operations. For instance 5 * 3 = 15 will put us in a weird pending state as soon as we hit *. Hitting = then finalizes the operation. Thinking about it, we are going to need a data structure that can remember the 5 * until we hit the = button.</li><li>Let’s add an equal operation, and a binary operation to our list of operations that our calculator can handle. Notice that the type of a binary operation should be one that takes two Doubles and return a Double.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*eQtIEjppRJAWFDJByg7DfA.png" /></figure><p>Add the corresponding operations to our dictionary. We will experiment with * for developing how we will do binary operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BDaiItnCW55sjI-7Rc7bEg.png" /></figure><ul><li>Where is our function multiply though?</li><li>Let’s create multiply as a global function at the top of our file, next to the function changeSign.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*Osuf5W1OwbjaeEiWcB38Ug.png" /></figure><ul><li>Before we can deal with the binary case in our performOperations method we should create that data structure that allows us to hold on to the pending operation eg. 5 *</li><li>Our data structure will be a Struct that holds our function and the first operand.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*4XiLsCQ8x-MXnpMOMSwLbw.png" /></figure><ul><li>In Swift Structs can have methods. We could add a method that given the second operand, will complete the binary operation. So for example, say we want to multiply 5 * 3 to get a result of 15, our PendingBinaryOperation data structure will grab on to the 5 *, then when it receives the second operand 3 it will perform the multiplication.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3runnS00nVL7k_d2zhTBew.png" /></figure><ul><li>This method on our PendingBinaryOperation doesn’t need to be marked as mutating because it isn’t actually changing the PendingBinaryOperation. We should also make this data structure private.</li><li>Let’s create a pending binary operation in our model</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*Mjhsku2qx-MX1lCnauiSVQ.png" /></figure><ul><li>We made it an Optional because we are not always in a pending operation, and in that case this variable will be in the Not Set state.</li><li>So when the user hits *, for example, which is a binary operation we are going to create a pending binary operation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Fg37D7nF_kwMHQiOJ1g0w.png" /></figure><ul><li>The first operand in this pending binary operation will be whatever is already in the accumulator, so we should make sure we safely deal with this since accumulator is an Optional. Also, when we are in this weird pending state, our accumulator is waiting for some result, so in this state it is nil.</li><li>What about when the = button is hit?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*87MC7HJXfrulHn5OVFmqHg.png" /></figure><ul><li>We made a function to perform the pending binary operation when the = button is hit.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*IOYr-FQ0eG90S-qvFZjoag.png" /></figure><ul><li>The ? after pbo does <strong>Optional Chaining</strong>. It unwraps the Optional. If the Optional is nil then it ignores the rest of the command. For now though, let’s just unwrap with the !, but make sure to check the pbo, and our accumulator is not nil.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*Tg_1-b7L6QLVLwqTlpw-0Q.png" /></figure><ul><li>Let’s set this result to our accumulator. We still get an error because we need to mark our function as mutating since it is modifying the state of our calculator brain.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*3jHFk2TQVhdaFvNp-Pvi2g.png" /></figure><ul><li>Once we have performed this pending binary operation we will no longer be in a pending binary operation so we set pbo to nil.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nayBoZJa4hSrN3lIrqusVA.png" /></figure><ul><li>pbo is a pretty bad name. Let’s rename that to something more descriptive, such as pendingBinaryOperation. Double click on pbo, click the arrow that appears next to it, then click edit all in scope. Type the new name and this will rename all occurrences of the old name with the new one.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sja6mij-4RlDg4D7kIR4hQ.png" /></figure><ul><li>pbo has been renamed to pendingBinaryOperation in our file.</li><li>Now that our Model is now fully equipped to handle binary operations let’s add some binary operations to our UI.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ffcW4_lHbt3eMvWQFZTBHA.png" /></figure><ul><li>Note that multiplication has the title x, and not *. Make sure to change that in the operations dictionary.</li><li>Since we also need to added ÷, x, –, and +, to our dictionary, perhaps we should add those functionality to our dictionary as well.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*25xyL9jdT_urfRsBWuha5g.png" /></figure><ul><li>Do we really need to now go and implement global functions like we did for multiply, and changeSign for minus, divide, and add? All of a sudden our new approach of using a dictionary appears like we haven’t gained much. How are we going to fix this?</li><li>We are going to use a feature in Swift called <strong>Closures</strong>. A closure is a function embedded right in-line our code.</li><li>We could actually replace multiply in our operations dictionary with the body and parameters of the multiply function we created.</li><li>Copy this from our function multiply, and paste it right in-line.</li></ul><pre>(op1: Double, op2: Double) -&gt; Double {</pre><pre>return op1 * op2</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aB38G7hcmfYR0LRyeq0r6A.png" /></figure><ul><li>It doesn’t quite work as yet, as we need to replace the open brace { with the word <strong>in, </strong>then place the { at the beginning.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3R0MqSMxj8nVkr2zdWlSXA.png" /></figure><ul><li>Now we don’t need that global function multiply in the beginning because the closure, which is an anonymous function is handling multiply right in line our code. This looks a bit ugly though. Let’s use Swift’s capability for type inference to make this look a lot neater.</li><li>Swift knows that since our closure is really a binaryOperation’s associated value, so it knows the type of op1, and op2. Basically, it knows the function prototype.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*WRANG1PhnzauLcljVXNMWA.png" /></figure><ul><li>Swift also knows our function returns a value, so we don’t need return. Placing this on one line, and we are definitely looking better!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uPqfImlz9ZEaSmH4LyqHBg.png" /></figure><ul><li>Swift also provide some argument names in the order $0, $1, $2…, so we can actually just get rid of op1, and op2.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*K9VguH_GYujeFptK_80QPg.png" /></figure><ul><li>Oh wow, aren’t we looking good! The essentials of what we are doing is write here without the distractions of extraneous types.</li><li>Now we can easily complete the table for the rest of our binary operations, even for our function changeSign, which we can now delete the global function.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lav8I7ASaLEM__3_pehe9g.png" /></figure><ul><li>Now we can add as many operations as we want with just one line of code.</li></ul><p><strong>Build and Run …</strong></p><p>Our calculator works!!</p><p>Let’s simulate a rotation of the device by clicking hardware in the simulator, and then one of the rotate options, or you can hold down command, and right arrow key. Our calculator is now unusable. We can’t even use the = button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDX8pWt8YoNMPqwR4FCGXA.png" /></figure><p>Our UI should be able to work in any orientation or for any device. Let’s get to it!</p><ul><li>Our basic design strategy would be to stack the rows of buttons on top of each other. Then stack this block of buttons together with our display to get one block of UI elements, then we will provide constraints for this block and the edges of our device.</li><li>Select a row of buttons, hit editor, then embed, then stack views. This operation is so frequent that we have a special button for it in Xcode in the lower right hand part of the screen.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*x1udcG1HwP_62fTZOY1zgw.png" /><figcaption>Embed in stack view is second from the left.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m6TEY6k30DAuZShw6Y56WA.png" /></figure><ul><li>As the attributes inspector indicate this is a horizontal stack view. Give it a spacing of 10, and make sure that distribution is set to fill equally, since we want all our buttons to be the same size. Repeat the above process for all our buttons.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tsZRs1JocX5NsYc_YkB75Q.png" /></figure><ul><li>Let’s now stack these horizontal stacks of buttons vertically. Select all the buttons and click on the embed in stack button. It’s smart enough to automatically provide a vertical stack,</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Je_y0x4dfIwlCGrX4Tsz4g.png" /></figure><ul><li>It did push them all to the left though. We want all our buttons to take up as much space, so let’s change the alignment of our vertical stack to fill, and of course we need some spacing. Set vertical spacing to 10.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DbDAhHVJ7Sm9zvoDh2Ldaw.png" /></figure><ul><li>Let’s now stack our display and our key pad. Select them both and embed in a stack. Set the spacing to 10, and set the alignment to fill.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kLvLVHL0yq7lTt8X9eqe7A.png" /></figure><ul><li>Now we have a beautiful looking UI as one block. All we need to do now is tie the edges of this UI to the edges of the device.</li><li>Select the entire block and use the guided blue lines to place it near the upper, and left margins as shown below.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JJZQzHpRai-YwAtYdQHOFg.png" /></figure><ul><li>Now control-drag from this block of UI elements towards the top of the canvas margins and a pop up with provide some options basically asking what kind of relation ship do you want the top edge of your UI to have with the top edge of the device. Select <strong>Vertical Spacing to Top Layout Guide.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xmGGRxBB_JSEW-g0xA499w.png" /></figure><ul><li>Do the same for the left, by tying it to the Leading Edge, then to the right, by the Trailing Edge, and then to the Bottom edge.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fuFFN7GkOHKlCx-lE3LujQ.png" /></figure><ul><li>Now our UI is pinned some distances from the margin. Double click on these blue lines for vertical towards the bottom, and horizontal towards the trailing edge and set the constant value to 0, or a standard value if available since we want our UI to be directly on these edges.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UKMNPFmyxCabpAgC48uGwg.png" /></figure><ul><li>It’s trying to stretch out one of the stacks. We need to set its distribution to fill equally.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CE3nHhzKaNID73pUwNxcpQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*46oxhsFrjr4kFNRoSK8UTg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AxSjaKIrG6BsUqsBW3sMgw.png" /></figure><blockquote>And that’s it for today! Now we have a perfectly working calculator that not only looks good in portrait, but when rotated in the landscape orientation as well.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14dd5d7c2e00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CS193P: Developing iOS 10 Apps with Swift Lecture 1 Notes]]></title>
            <link>https://medium.com/@seabjackson/cs193p-developing-ios-10-apps-with-swift-lecture-1-notes-250d93e5bf33?source=rss-8df11fc7fc9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/250d93e5bf33</guid>
            <category><![CDATA[cs193p]]></category>
            <category><![CDATA[stanford]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Seab Jackson]]></dc:creator>
            <pubDate>Mon, 27 Feb 2017 22:03:50 GMT</pubDate>
            <atom:updated>2017-02-27T23:27:56.113Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*00oUEIgfUzb0hqn1sVUz4Q.png" /></figure><ul><li>These are basically the notes taken from my undertaking of this iOS course. In many ways the notes are verbatim what the professor has said. The lecture slides are also those provided in the materials section for the course on iTunes U. These notes are really meant for me, but could be useful for others going through the course, and wanting a way to refresh their thoughts on what went on in the lectures without having to rewatch the lectures, or as supplementary to them. I will add my own input in various areas, and provide examples, or other insights to further an understanding of the concepts taught in the class. It is my hope that these notes will not merely be helpful to me, but to others on a mission to become excellent iOS developers!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CgLMIBm0pthlHABc2nZnmw.png" /></figure><ul><li>The class does have some prerequisites, which one would do well to meet. The major one is experience in <strong>Objected Oriented Programming</strong>(OOP). Relevant Stanford Courses to fulfill the requirements are <strong>CS106A&amp;B</strong>, <strong>CS107</strong>, <strong>CS108</strong> or <strong>CS110</strong> This is an upper level CS course at Stanford University. I myself don’t meet all the prerequisites, but am not going to let that stop me from pursuing my objective.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rm4NV4iABOAn4sW4AKEAnQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KlvJ9QzN36XTm-jxG_ieYg.png" /></figure><p><em>Think of these as four layers with the ones at the bottom closer to the hardware, and those at the top closer to the user.</em></p><p><strong><em>Core OS</em></strong> is near the hardware whereas <strong><em>Cocoa Touch</em></strong> is near the User.</p><ul><li>An iPhone is running <strong>UNIX</strong>, so it has full multi-tasking and File System. When you build an app you have access to all these capabilities. Specific to mobile devices are things like <em>Power Management</em>, and <em>Keychain Access</em> (to ensure people aren’t accessing things they shouldn’t be.) These APIs are pretty much written in C, and we won’t be doing any work in this layer.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uWKWWFYWrqJplCsW1_SJyg.png" /></figure><ul><li>An object oriented layer on top of UNIX is the<em> </em><strong><em>Core Services</em></strong> layer so that we can get to things like <em>Networking</em>, <em>Multithreading</em>, or <em>Preferences</em> and <em>SQL</em> for databases.</li><li>There is no <strong>User Interface</strong> (UI) in this layer. This layer is referred to as <strong>Foundation.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EhGVMcf1UU9sxAJ5umTpzg.png" /></figure><ul><li>This (Multimedia) is a super important layer that ironically we won’t get to spend too much time on.</li><li>This layer includes videos, all kinds of different audio frameworks, still pictures like JPEGs, the Quartz API for drawing in 2D, OpenGL for drawing in 3D etc.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NnNRbDfji-LI-bh2aYkq7Q.png" /></figure><ul><li>At the top layer, which is where we will spend most of our time is <strong>Cocoa Touch</strong>.</li><li>It is object-oriented API for building user interfaces.</li><li>These user interfaces aren’t limited to things like buttons and sliders on a screen. They include for example, what to do when you shake your phone, and using the orientation of the phone as input. It also includes animation.</li><li>We won’t have time to go through all the objects in this layer, but the idea is that some of the objects we learn about will have paradigms for using them that we can apply to those we are unfamiliar with.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a4ZkeoTiO03TXWDKUXJQUA.png" /></figure><ul><li>Everything we do will be in Xcode 8 (or later), and we will be doing everything in the relatively new programming language, Swift.</li><li>Just as important as the frameworks is a design strategy or methodology called <strong>Model-View-Controller (MVC)</strong>.</li><li>Model-View-Controller is a way of dividing all the classes in our Object Oriented app into three different groups. The <em>Model</em> group is what our program does that is UI independent. For a calculator, that’s going to be all the calculating. How to add, divide, square root etc. The <em>View</em> is the user interface that the user interacts with. It is typically made with generic user interface elements like buttons and sliders. For the calculator, that’s going to be the buttons and the display. The <em>Controller</em> is the glue between the <em>Model</em> and the <em>View</em>. It’s the thing that listens to what’s happening in the UI, makes decisions, updates the Model, or perhaps updates the UI due to some changes in the Model.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rTBDvVRKYPKeVAWlvbk1nw.png" /></figure><p>We will be building a Calculator!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FP5wg__7M9bpqoy1shAyCA.png" /></figure><p>Our calculator will be similar to this macOS calculator in basic functionality, and UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dNZbyVeSA46Cxyoiwz6b1g.png" /></figure><ul><li>Once we have our project set up in Xcode, this main.storyboard file is where we design our API. Notice that there is no code in this file. We are just going to drag objects from the Object Library unto this canvas and design our apps as though we are painters using a palette of objects.</li><li>Currently we have the canvas set to “View as: iPhone 7”. We can typically choose any of the iPhones that Apple has produced to design our apps for, but really what we want to do is to design an app that can work on all the various devices regardless of screen size. This system for designing our apps, which is called <strong>Interface Builder</strong> has all the necessary tools and technologies for allowing us to build that universal app. That technology is called <strong><em>Auto Layout</em></strong>.</li></ul><p>Well let’s get on to building our Calculator. We are most certainly going to need buttons, and a display. Where do we find these? Let’s take a look at the utility section in Xcode, and then scroll through the object library. It has things like, buttons, sliders, maps, image views, textfields and all the tools we can use to build our apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dSvlNKmJDNuKFDyLJTdFng.png" /></figure><ul><li>Here we have dragged a button object unto our empty canvas.</li><li>Double tap on this button and type 7, then use your mouse to size the button to 64 X 64.</li><li>The text is still too small, so still in the utility inspector change the font-size to 30, then scroll down to the view section of the utility inspector and change the background color to whichever color you wish.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qKMDRQg0LUM9fMgLPIC_XA.png" /></figure><ul><li>Let’s run the app! When we do so, and press on our button of course nothing happens. That’s because we haven’t written any methods, or actions for our button. We need a way to connect this button to code that we will write.</li><li>The behavior of our UI is written in code. Currently we will write that in the class ViewController. That is a rather generic name, and a better option would probably have been CalculatorViewController, but let’s just go ahead for now.</li><li>To connect the UI up to the code we need both files on screen at the same time. We can use the assistive editor to do this.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*sVZs7SOe96mzseVnJeMhmw.png" /><figcaption>Click the assistant editor to get the View and the Controller on the screen at the same time.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*06CAbTIyouZW5MuKW1dHGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*ZkfOYz9RJGMNjos-NDJLWQ.png" /></figure><ul><li>This is our first look at Swift!</li><li><strong><em>import</em></strong> is like include in other languages. We are including <strong>UIKit</strong> which is a <em>module</em>, and not a file. In Swift, we can group a number of classes together and call it a <em>module</em>. All those classes, provided they’re public will be visible to whatever is using it.</li><li><em>UIKit</em> has all the User Interface elements we can use to build the calculator app like labels, buttons, and textfields. We almost invariably will be importing UIKit.</li><li>In the Model, since it’s UI independent, we would most likely be importing <strong>Foundation</strong>. <em>Foundation</em> is that <em>Core Services</em> layer as we could be doing networking and databasing in our Model.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*nGP9OWifn3UrrHBUgeRA3g.png" /></figure><p>This is how we can define a class in Swift.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*__xNGrLTJPpSDb9uh_vUdw.png" /></figure><ul><li>In Object Oriented Programming (OOP) classes have <em>inheritance</em>. <em>UIViewController</em> is the class our controller inherits from. Note all<em> MVC </em>controllers must inherit from <em>UIViewController</em> directly, or indirectly.</li><li>So now what we want, is that when we click on the button, it should invoke a method in our class.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3qH6OHmOhGyYDoYMUg8Cjg.png" /><figcaption>Control drag from the button into your code to make a connection</figcaption></figure><ul><li>Once you make the connection, you have two options (Outlet, or Action) to indicate what kind of connection you want to make between the user interface element and the <em>Controller</em>. In our case, we’ll choose Action because it is used for allowing something that happens in the UI (some action) to invoke a method in the <em>Controller</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*aJ5uPc-_kdvJQUYYY27Sfg.png" /></figure><ul><li>The name of this method will be “touchDigit”. One might need to change the generic type <em>Any</em> to type <em>UIButton</em>. Note that this method takes arguments. In this case the sender is the argument which will prove useful because in the case of a calculator, we want each digit pressed to be able to tell us what it is.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*gb1USDGL37wfxfxM9HuYMA.png" /></figure><ul><li>That @IBAction is actually not really Swift. That’s just something that Xcode adds, and it fills a little dot in the gutter such that when we mouse over that dot we see which of our interface elements is sending that method.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2-6DWnpXxJyvIfj8yDn5MA.png" /></figure><p>Here is the basic make up of a function in Swift.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*29oft9wlEAYKxYs7399gAA.png" /></figure><ul><li>We start with the func keyword, then the name of our function. In the above example our function has 3 parameters. After the colons we specify the types of these parameters, so the types of our parameters to this function are Double, Double, and UIColor respectively.</li><li>Interestingly though, our parameters have two names. The first is called the <strong><em>external</em> parameter</strong>, and the second are our <strong><em>internal</em> parameters</strong>. Here our external parameters are ‘from’, ‘to’, and ‘using’. Our internal parameters are: ‘startX’, ‘endX’, and ‘color’. We use the internal parameters when implementing the function, but the external parameters when calling the function.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y98Dufe3u1urMmU4n4vATQ.png" /></figure><ul><li>As shown above, the internal parameters were used to find the distance. We then called this function from the action touchDigit using the external parameters, ‘from’, ‘to’, and ‘using’.</li><li>Swift aspires to be as conversational as it can be. In other languages we might call drawHorizontalLine as drawHorizontalLine(5.0, 95.0, blue). In swift we must call the function with the external parameters. If however, we do not want to call the function with the external parameters we can use _ to signify that, as in the touchDigit method above where the function only has an internal parameter sender. We use _ in many instances where it is implicit from the name of the function, the value that we need to pass into it. Typically we only use _ for the first parameter.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*s605Uyzl5HpdvcjejhMBOQ.png" /></figure><ul><li>This allows us to print “touchDigit was called to the console each time that we press the button”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d4LcU43XSF9fPAuG6L2knA.png" /><figcaption>pressing the digit thrice produces this output</figcaption></figure><p>We know that we need more than one button for our calculator, so copy and paste the first button a number of times then double tap the button to change the digit name. The end result should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uoNI4KSas1DqKFWDITpnoQ.png" /><figcaption>Create the number pad</figcaption></figure><p>What’s great is that because we copied and paste the buttons, all our buttons can invoke the touchDigit method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PufI4RHaFrbrf2LM168-0A.png" /><figcaption>mousing over the touchDigit connection in the gutter shows all our buttons can invoke it</figcaption></figure><ul><li>Now if we build and run the application we’ll see that each time we press any of the buttons, it will print to the console “touchDigit was called.”</li><li>That’s cool and all, but for a calculator we want to know what digit we pressed. We know that we can get that because touchDigit has an argument of sender. The sender can tell us its title or value!</li><li>Let’s create a local value to store this title, or value, but before we do that we send message to objects in Swift using the dot syntax. Thus, since sender is the button we will say sender.someMessage</li><li>How do we know what we should send to our button though?</li><li>Let’s take a look through the Apple documentation on UIButtons.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jTpN_huovD8pBOA6bkJm3g.png" /></figure><ul><li>Perusal of the documentary for UIButton reveals that we can use the currentTitle property to get the value of the digits we press on our calculator. What’s up with type of currentTitle though. It’s a String? huh? Before we get into what that type it is, note also that the <em>{ get }</em> is basically saying that we can never set the <em>currentTitle</em> property, we can only get it. Thus, it’s read-only.</li><li>Let’s print out the value of the digit stored in our local variable digit,.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*KaNquT2XqxLFAv6N586HFQ.png" /></figure><ul><li>We’re storing the button’s <em>currentTitle</em> property in some local variable, digit. The syntax <em>\( )</em> in the print statement is called <strong><em>String Interpolation</em></strong>. It evaluates whatever is within the parentheses and converts it to a <em>String</em>, <strong>if possible</strong>. We do have a warning though! Let’s click on it to see what that’s about.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*hZrx0K6YaHnusgltjyOAaQ.png" /></figure><ul><li>Any time you declare a local variable or property that never changes after it has been initialized, always use <strong>let</strong> instead of <strong>var. Why distinguish between let and var when declaring a constant?</strong></li><li>There are two main reasons. Firstly, it’s easier for others reading your code to know that the variable never changes, and is as such a constant if we use let. Secondly, if the variable you declared with <em>let</em> was an <em>array</em> or a <em>dictionary</em>, that <em>dictionary</em> or <em>array</em> would be <strong>read-only.</strong></li></ul><h4>Run the simulator…</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dNt7bRGodU1mJ6i-teV8xw.png" /><figcaption>pressed digits 7, 1, and 8</figcaption></figure><ul><li>Hmm what’s this <strong>Optional</strong> in our output? Well, Ok take a deep breath because <em>Optionals</em> are very important in Swift, and ubiquitous throughout the entire iOS API.</li><li>In Swift, there is a type called <strong>Optional</strong>. Just like <strong>Int, Double</strong>, and <strong>Bool</strong>, it’s a type. This type can only have two values, or states: <strong>Not Set</strong> and <strong>Set</strong>. <strong>Not Set</strong> is expressed in Swift with the keyword, <strong>nil</strong>. If the <em>Optional</em> is in the Set state then it can have an <em>associated value</em> which can be of any other type.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*CeORbiGSi5xARcq_Dn9qow.png" /></figure><ul><li>What is the type of <em>currentTitle</em>. It’s an <em>Optional</em>, and its associated type is <em>String</em>. Why is it an <em>Optional</em>? Well, we might have a button that we haven’t given a title yet, so it needs to have the case for when it is <strong>Not Set.</strong></li><li>Why didn’t we declare <em>digit</em>, like so:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*HfC_djK_BOStyKiGoer5ng.png" /></figure><ul><li>That’s because Swift can infer the type of <em>sender.currentTitle, </em>and it’s bad coding style to do so explicitly when it can be inferred. This capability of Swift to infer our type will make our code much more compact.</li><li>So if the button title is <strong>Set, </strong>how do we get that actual associated value of String? We put an <strong>!</strong> in the end. The <strong>!</strong> unwraps the Optional to give us the associated value.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*V3Pe7oFiPyE8txWa6SWx_A.png" /></figure><ul><li>What would happen is we tried to unwrap, using <strong>!</strong>, an Optional that was in the <strong>Not Set</strong> state? It would crash our program!</li><li>Don’t be apprehensive towards using <em>Optionals</em> because you think your programs would be crashing all the time. In fact, crashing your program can be a good thing! Finding bugs that crash your program because they weren’t set at an expected time before you ship your app to the customer is certainly helpful.</li></ul><p><strong>Build and Run…</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*H1PpT7b87ZANeWUHPX5r3w.png" /></figure><ul><li>Now when we run the program and press the buttons 7, 1, 8 we get the correct output of the button that was touched.</li><li>This is all nice, and good, but what we really want is for our calculator to have a display such that when we press the digits they show up in our display. Let’s get to it. Drag a Label unto the canvas.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*neXIQNIRmOMANrkqH6_lkg.png" /></figure><ul><li>We could make the Label have a font-size of 40, and make the text/digit right-aligned like most calculators. We can also change the background color, and color of the text to whatever we please.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1AVmxjEl9HVIWObUCF7Ibw.png" /></figure><ul><li>How about connecting this Label to our <em>Controller</em>? In this case it will be a bit different. This is not the case, like the buttons, where we wanted a touch on the button to invoke some method in the controller. This is the other way around. We want to talk to it, so we need an instance variable that points to this display so that we can add things to the display. In essence, we want communication to be from the <em>Controller</em> to the display. This type of connection is called an Outlet.</li><li>Control drag from the display to the <em>Controller</em>. This time we’ll choose an Outlet. An Action is a method, but an Outlet is a property.</li><li>Control from the UILabel into our code and name this outlet <em>display</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*Qyp2IRBZU7J58pW9mCR_cw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*SzxTrRlFkRKDaRHxqSicnw.png" /></figure><ul><li>@IBOutlet is just something Xcode adds to indicate an outlet.</li><li>What’s the type of our display though. It’s type is <strong>UILabel!</strong></li><li>As you might suspect the exclamation mark ! at the end might indicate that display is an optional. Wait a minute though, wasn’t ! used to unwrap an optional? Well, that’s true, but when declaring a variable the ! can be used to say this variable is an Optional, but with a slight twist. For now let’s just think of this <strong>UILabel!</strong> as though we had declared it as <strong>UILabel?</strong> to mean it was an optional. Go ahead and change ! to ?. The distinction between using ? or ! to indicate an Optional type will be revealed shortly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*ZO76Skm6B-s6-ZqVc8YkTQ.png" /><figcaption>Change the ! to a ?</figcaption></figure><ul><li>Why is the UILabel an Optional though? That’s because when the UI first loads up, iOS will take a few nanoseconds before it connects up this UILabel. In those few nanoseconds, the UILabel will be in the Optional “Not Set” state. Then once it is hooked up it will be in the “Set” state forever. That latter point of being set forever once it has been set is an important insight. Since we change display to type UILabel?, it just means we need to unwrap display with ! everytime we use it.</li><li>Let’s now tackle how we append the digit pressed to the display. We basically just need the text that is currently in the display, and add the digit to it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*-CTR5Ndn5VIE-mNW4g8H7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdl5VNuBhsdf_BWfH4SvtA.png" /></figure><ul><li>Notice that we have to unwrap display each time we use it. The property, <em>text</em>, for the UILabel, our display in this case is an Optional String, so we have to unwrap it as well. Note also that ‘text’ has a {get set} unlike currentTitle, which was only { get }. This means that ‘text’ isn’t read only, so we can set its value. When we set the value of an Optional we do not need to unwrap it, so we say: display!.text = …. to set the text property of our display.</li></ul><p><strong>Build and Run …</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JUv8nIuf-itgOcpT5-VRLQ.png" /></figure><ul><li>It works! There is one issue though. That zero(0) at the end isn’t really how a calculator works. When pressing 1, 2, 3, the display should be 123. When typing a new number, that <strong>0 </strong>shouldn’t be there. We need a way to keep track as to whether we’re in the middle of typing a number. If we are , then we append, but if we’re not then just replace the display with the new number.</li><li>Let’s create a Boolean property that keeps track of when the user is in the middle of typing a number</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D1lZJ2aKGPFSmdLhbcD1GA.png" /></figure><ul><li>Firstly, our variable name is exceedingly long! Though for effect, there is a case to be made that though brevity is important, clarity is even more important.</li><li>When we added this variable and tried to run the simulator, we get an error that Class ‘ViewController’ has no initializers. How come? Well in Swift <strong>ALL</strong> properties must be initialized to some value. Now, There are two ways we can initialize a value. We can just give the variable a value from the outset, or we can create an initializer which must initialize all uninitialized variables.</li><li>Let’s just use the simpler method and set <em>userIsInTheMiddleOfTyping</em> to <em>false</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*kot9pCEoQ3AK6swmHGqkow.png" /></figure><ul><li>We no longer need to declare the type as <em>Bool</em>, because Swift can infer the type since the variable was initialized to a Boolean value of <em>false</em>.</li><li>One objection you may have then is that we didn’t initialize our Optionals like so:</li></ul><pre>@IBOutlet weak var display: UILabel? = nil</pre><ul><li>That’s because Optionals are treated specially. They are always automatically initialized to <em>Not Set</em>. That is, <em>nil</em>.</li><li>Now we can just add the digits we press to the display if the user is in the middle of typing, but let the display be the digit otherwise because in that case we would be starting a new number.</li></ul><h4>Code Logic Pseudocode</h4><pre>userIsInTheMiddleOfTyping = false</pre><pre>if userIsInTheMiddleOfTyping<br>     append the digit<br> else <br>     display the new digit</pre><pre>set userIsInTheMiddleOfTyping to true</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*YiOwg6Kny3trZ2bUS-IRoQ.png" /></figure><p><strong>Build and Run …</strong></p><p>Seems like it’s working correctly, but we can’t call this number entering app a calculator as yet because we have no operations. Let’s change that.</p><ul><li>Copy and paste one of the buttons to create a pi button for an operation of pi. (This is a bad idea as we’ll soon see.)</li><li>This button will be an operation that displays π in the display. (Hold down <strong>alt + p</strong> to get the π symbol)</li><li>Control drag from the π button to our class to create the performOperation method.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ly6Mkd7NhX_aY_FshrIIKg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*XrjagjbAj5Mh_auBIYfUAA.png" /></figure><ul><li>Since we will have all our mathematical operations invoke this <em>performOperation</em> Action we’ll need to know what type of operation the button wants:</li></ul><pre>let mathematicalSymbol = sender.currentTitle!</pre><ul><li>Notice that because we want the <em>String</em>, we need to unwrap the <em>currentTitle</em>. What if there was no <em>currentTitle</em>, and that instead of crashing we just wanted to ignore it. We’ll basically just want to unwrap only if the <em>currentTitle</em> was <em>set</em>.</li></ul><pre>if let mathematicalSymbol = sender.currentTitle {</pre><pre>}</pre><ul><li>The above reads as if I can <em>let</em> my <em>mathematicalSymbol</em> equals the sender’s <em>currentTitle </em>then do something. This is the safe way to unwrap <em>Optionals</em>.</li></ul><p>If the symbol is π then update the <em>display</em> with it:</p><ul><li>Once we can safely unwrap the mathematical symbol we might want to pattern match to check which mathematical operation we want to perform. We can do this with a bunch of if else statements, but lets opt to use Switch instead. Switch is more powerful in Swift than in other languages.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*82gvi9us1vUb6T7B0iyeVQ.png" /></figure><ul><li>Let’s ignore the fact that I have hardcoded a string value for π. We do have a warning. Swift cases must be exhaustive. Since we can’t possibly cover every mathematical operation that might exist or come into existence, we can use the default clause to cover any case that we don’t know about, or that our calculator won’t support and just break.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eatDfmGqwNfu--TPQPCq5Q.png" /></figure><blockquote>Note a neat little trick to indent your code is to highlight all the code you want to properly indent and then hold control and i together on the keyboard.</blockquote><p><strong>Build and Run …</strong></p><p>Oops…We now have three issues. If we type too many numbers in the display we get an ellipsis, our π button is very weird as it is adding the π symbol to the value of π, and after pressing π, and then a digit the new number is appended to the π symbol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FAp2jK-_7k8PlObZvO-3MQ.png" /></figure><ul><li>Let’s tackle the π problem. Here’s the issue. Because we created the π button by copying and pasting the number buttons, our π button is invoking two methods. It’s invoking the <em>performOperation</em> method, but it is also invoking the <em>touchDigit</em> method in our <em>Controller</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GpdDXZySe8LFN-V96QOOEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*uyN3nd9OXFgsEb43FqtDVg.png" /><figcaption>When we hover over the touchDigit button in the gutter, the π button is highlighted along with the other digits</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*RXABe11uK9GlGUlWd-xJ9Q.png" /><figcaption>Right Click the π button brings up its list of connectioins</figcaption></figure><ul><li>When we look at the connections of the π button, we see that it is connected to touchDigit, and performOperation methods at the same time when we ‘touch up inside’. That basically mean when we touch within the bounds of the button. We can fix it by clicking the little x next to touchDigit.</li><li>Whew! Next problem is that after pressing π and then another number button, it was assuming that we were in the middle of typing a number and appending those digits to the end of the π value. We can solve this by just ensuring that when we add any mathematical operation, we are not in the middle of typing a number.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*04j4c5FgEjY0RtayMgPx8g.png" /><figcaption>Whenever we add an operation the user is no longer in the middle of typing a number</figcaption></figure><ul><li>How about the ellipsis when we have too many numbers in the display? Though this isn’ t the optimal solution, there is a neat feature in UILabel called Autoshrink where we can set the minimum font size. Let’s set it to 9. That way when there are too many numbers in the display for it to show them properly it will just shrink the font-size of the digits in the display to show them all.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*qy3nzsLuvyKn6-bSzpxMqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uyKTpF6sSQowH6BQdTuaIg.png" /></figure><ul><li>When we Build and Run, the three issues highlighted above seem to have been resolved.</li></ul><p>What’s next, well we really don’t want to be hardcoding π. It’d be nice if we can get its value to be what is already provided as Double.pi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UbTbR_BPFPHabYyDCFywHA.png" /></figure><p>Let’s try setting the display’s text to this value of pi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EBWSdwZAZayPMFwA0lUmvQ.png" /></figure><ul><li>Not surprisingly, we get an error because the ‘text’ property is expecting a String, but pi is a Double. We need a way to convert pi to a String.</li><li>Isn’t there something we learned earlier that evaluates an answer and converts it to a String. Yes, String Interpolation with the syntax \( ). Perhaps we could evaluate Double.pi and convert it to a String, like so:</li></ul><pre>display!.text = “\(Double.pi)”</pre><ul><li>This works, but is a bit ugly. String Interpolation is really meant to embed other things into a String. How can we create a String? Well, in Swift, to create a new Class, Struct, or Object we can just provide the name of the class with parentheses. We can create a String like this:</li></ul><pre>String()</pre><ul><li>Whatever is inside the parentheses would be anything the class can take as an input to create one of itself. Those are its arguments to its initializers. A class can have multiple initializers. String has a ton, and one of them is that it can take a Double. So the best way to convert pi to a String then would be like this:</li></ul><pre>display!.text = String(Double.pi)</pre><ul><li>This makes it more obvious as to what we are really doing, that is converting from Double to a String.</li><li>Let’s add another operation to our calculator. How about square root √</li><li>Add another button by copying and pasting the pi button since it has the performOperation method already. Change the button’s title to √. (hold alt and V together to get the √ symbol)</li><li>Now all we need to do is add the case for square root. We want it to be the square root of what is already in the display.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s5NnJsBwaMcq2Vzsbysc1g.png" /></figure><ul><li>This doesn’t work because the input of sqrt( ) must be a Double, whereas display!.text! is a String. We can’t find the sqrt( ) of a String. Also sqrt( ) returns a Double, so we cannot set it into the display!.text directly before converting to a String. Phew!!, so we have to convert.</li><li>Let’s break this down a little, so we can work with it. The operand of sqrt( ) should be a Double so create a local variable for this.</li></ul><pre>let operand = Double(display!.text!)</pre><pre>display!.text = String(sqrt(operand))</pre><ul><li>Can we do this? Well yes, but unlike the conversion from Double to a String, we are trying to convert our operand from a String to a Double. In the case where for example our String is “123”, it might return 123.0, but in the case where out String might be “hello”, how can we convert that to a Double? We can’t, so our Double(someString) will return an Optional Double because there are instances when we can get the Double from a String, and other cases when we can’t. Since operand will be an Optional Double we will need to unwrap it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*UyFpt7bjf8KTcGdL8OQwYQ.png" /></figure><p><strong>Build and Run…</strong></p><ul><li>Our calculator is working perfectly, but our code is such a mess. Look at all these ! in our code. Also, what happens when we add another case? Do we have to go do these String, to Double, Double to String conversions all over again? Let’s tackle the first issue.</li><li>Look at all these ! after <em>display</em>. We are unwrapping the <em>display</em> each time we use it even though we know that’s once the display is set up by iOS in the beginning it will always remain set. So go back to where we declared the display, and switch the ? to an !.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*tv5rYO3eA0NMnSPAEEzZmw.png" /></figure><ul><li>This is what ! means in a declaration. It’s saying this variable is an Optional just like ?, but everywhere you use it afterwards, it will automatically unwrap. So we can go back in our code where we have always manually unwrapped our display and remove the !, and our code will still work. Essentially, adding ! in the declaration of an Optional variable will implicitly unwrap that variable. The term to describe this type of variable is an <strong>Implicitly Unwrapped Optional.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yz8hVjavQLyxYVPE_4au6A.png" /></figure><ul><li>Now our code looks quite a bit nicer, so now let’s tackle all these dang type conversions.</li><li>Since we always need the value in our display as a Double to perform operations on, wouldn’t it be cool if we had a way to keep track of what is in the display, say in a variable called displayValue, but as a Double rather than its current type of String? Well we’re in luck because Swift has this cool feature of a <strong>computed property</strong>. All we do is put code after the variable, and we can compute its value rather than storing it. It can have a get case and a set case.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*OrG6euSWB8LFmjH-mR8rZQ.png" /></figure><ul><li>To get the displayValue as Double we just convert whatever is already in the display as a Double. Note we are unwrapping text because it isn’t an Implicitly Unwrapped Optional, and we have the second unwrapping because converting from String to Double gives us an Optional Double, so we need ! to unwrap that associated Double value. How about setting the display value? We need to set the display’s text to a string of some new value that we want in our display. There is a special keyword called newValue that we can use. It will always be the same type as the variable we are setting, so obviously newValue is of type Double.</li><li>Now since we have something that keeps track of our displayValue as a Double we can clean up our code even further.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*ejcva-KlM6vPocMHizMIoA.png" /></figure><ul><li>How beautiful is that! For the π operation we just want to put π on the screen, so we compute the set case of our displayValue. When we want to find the √ of what’s in our display the we compute the get case of our displayValue.</li><li>We had already seen a computed property before. currentTitle recall had a ‘get’ so it basically computed the title of the button and returned whatever that title was.</li></ul><p><strong>Build and Run …</strong></p><p>Voila! It still works with this arguably better code design. Next time we are going to put our code design on steroids when we ensure that our code fits MVC conformance, and also delve into how we can create universal apps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=250d93e5bf33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CS 193P: Developing Applications for iOS with Swift Lecture 1 Notes]]></title>
            <link>https://medium.com/@seabjackson/designing-ios-apps-with-swift-lecture-1-805950e1d006?source=rss-8df11fc7fc9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/805950e1d006</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Seab Jackson]]></dc:creator>
            <pubDate>Fri, 13 May 2016 21:10:18 GMT</pubDate>
            <atom:updated>2016-09-20T07:38:37.619Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pTJlmthcmusWFWhk3bmBsA.png" /></figure><h3><strong>Introduction</strong></h3><p>In my quest to become a master iOS Developer, Stanford University’s CS193p: <strong>Developing iOS (9) Apps in Swift </strong>is a course that was championed by many as a huge concomitant to their success in iOS Development. It came though, with a caveat that it wasn’t necessarily the best course for novice programmers. I have just completed a batch at the Recurse Center (Hacker School), and have been inspired to tackle problems far beyond my comfort zone. Taking this course is one such feat. These are the notes that I have taken to help me further understand the material, and to prevent me from having to pause and replay the videos ad infinitum. Many of the slides are provided through the iTunes U course. The notes are meant for me, and are really a dictation of what was said in the lectures, but I was urged to share them as they have proven useful for many folks going through the course as well. I don’t even meet half the prerequisites, and as such I suspect my notes will be quite verbose, and possibly more suitable to relatively new programmers like myself. Please post any suggestions for improvement below. Thanks!</p><ul><li>Prerequisites</li><li>iOS Overview</li><li>Demo</li><li>What will you learn?<br>- You will learn how to build “cool” apps<br>- Real life Objected-Oriented Programming</li></ul><p><strong>Prerequisites</strong>: The major prerequisite is experience in <strong>Objected Oriented Programming</strong>(OOP). Relevant Stanford Courses to fulfill the requirements are <strong>CS106A&amp;B</strong>, <strong>CS107</strong>, <strong>CS108</strong> or <strong>CS110</strong> This is an upper level CS course at Stanford University.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AoymGLkpgcZo-dNcYM4lrg.png" /></figure><p><strong><em>Core OS</em></strong> is near the hardware whereas <strong><em>Cocoa Touch</em></strong> is near the User.</p><ul><li>An iPhone is running <strong>UNIX</strong>, so it has full multi-tasking and File System. When you build an app you have access to all these capabilities. Specific to mobile devices are things like <em>Power Management</em>, and <em>Keychain Access</em> (to ensure people aren’t accessing things they shouldn’t be).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6zixPrg61BuhKxtI96W3Rg.png" /></figure><ul><li>An object oriented layer on top of UNIX is the<em> </em><strong><em>Core Services</em></strong> layer so that we can get to things like <em>Networking</em>, <em>Multithreading</em>, or <em>Preferences</em> and <em>SQL</em> for databases.</li><li>There is no <strong>User Interface</strong> (UI) in this layer.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fpazm4DGqo75fkr9sDInTQ.png" /></figure><ul><li>This (Multimedia) is a super important layer that ironically we won’t get to spend too much time on.</li><li>This layer includes video, all kinds of different audio frameworks, still pictures like JPEGs, the Quartz API for drawing in 2D, OpenGL for drawing in 3D etc.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FfOzim4BHIoOcIXh34xAVg.png" /></figure><ul><li>At the top layer, which is where we will spend most of our time is <strong>Cocoa Touch</strong>.</li><li>It is object-oriented API for building user interfaces.</li><li>These user interfaces aren’t limited to things like buttons and sliders on a screen. They include for example, what to do when you shake your phone, and using the orientation of the phone as input. It also includes animation.</li><li>We won’t have time to go through all the objects in this layer, but the idea is that some of the objects we learn about will have paradigms for using them that we can apply to those we are unfamiliar with.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJVKDoBd9Hb8jioxSgiaSA.png" /></figure><ul><li>Everything we do will be in Xcode 7, and we will be focusing on Swift throughout.</li><li>Just as important as the frameworks is a design strategy or methodology called <strong>Model-View-Controller (MVC)</strong>.</li><li>Model-View-Controller is a way of dividing all the classes in our Object Oriented app into three different groups. The <em>Model</em> group is what our program does that is UI independent. For a calculator, that’s going to be all the calculating. How to add, divide, square root etc. The <em>View</em> is the user interface that the user interacts with. It is typically made with generic user interface elements like buttons and sliders. For the calculator, that’s going to be the buttons and the display. The <em>Controller</em> is the glue between the <em>Model</em> and the <em>View</em>. It’s the thing that listens to what’s happening in the UI, makes decisions, updates the Model, or perhaps updates the UI due to some changes in the Model.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*VnY3V-ptXMwgNGQCPGiQfg.png" /></figure><ul><li><strong><em>import</em></strong> is like include in other languages. We are including <strong>UIKit</strong> which is a <em>module</em>, and not a file. In Swift, we can group a number of classes together and call it a <em>module</em>. All those classes, provided they’re public will be visible to whatever is using it.</li><li><em>UIKit</em> has all the User Interface elements we can use to build the calculator app like labels, buttons, and textfields. We almost invariably will be importing UIKit.</li><li>In the Model, since it’s UI independent, we would most likely be importing <strong>Foundation</strong>. <em>Foundation</em> is that <em>Core Services</em> layer as we could be doing networking and databasing in our Model</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_J4MaUFtKabuTDrn8JSAYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k_cVzGpl8bMGMvfprPFhFg.png" /></figure><ul><li>Note the name of our class is <em>ViewController</em>, and is too generic. It is good practice to make descriptive class names. For instance, in the case that we are building a calculator, it might be better to call this CalculatorViewController.</li><li>In Object Oriented Programming (OOP) classes have <em>inheritance</em>. <em>UIViewController</em> is the class our controller inherits from. Note all<em> MVC</em> controllers must inherit from <em>UIViewController</em> directly, or indirectly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b78QXiVuCOE2QBgiRC7iVw.png" /><figcaption>Empty canvas</figcaption></figure><ul><li>The Main.storyboard is the V (View) of our M<strong>V</strong>C. That is, the graphical representation of our calculator. Interestingly, this UI is square. Trick question: How many iOS devices are square? The answer is NONE. They’re all rectangular.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*gK7F1BefvlirCDl9nMLGjg.png" /><figcaption>Whether in portrait, or landscape, the devices are all rectangular.</figcaption></figure><h4>Why then do we design in a UI that is a square?</h4><ul><li>We do so to remind ourselves that we need to design our UI such that it can stretch and expand in any direction, so that it’ll fit in any shape. The appeal is that we can build one UI, that will work on all the devices.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TEtlq5B4k0RtBxXxlmOi0w.png" /></figure><ul><li>Like an artist, we paint this empty canvas with UI elements. Here we dragged the button from the utilities menu on to the canvas and placed it in the <em>conceptual</em> center. The dotted blue lines are there to facilitate in building this flexible, adaptable UI.</li></ul><p><em>*</em><strong><em>Note for the purposes of this Demo, we won’t adhere to those design practices just yet</em></strong><em>.</em></p><ul><li>We can use the attributes, and size inspector to edit the UI elements.</li><li>Change button size to 64 x 64, and the font size to 30.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*nDJfCqdqktohCvHkcZlKyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HkOLhniI7uknU8YBRss7iA.png" /><figcaption>font size changed to 30, and background color changed to mercury.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0-kOltbWmTaLwooq84PhFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*O40KkVF2O_ORnM0VvWr5og.png" /><figcaption>size of button changed to 64 x 64</figcaption></figure><h4>Run the Simulator . . .</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7dPDRYjOl7h_sEpEWHGuQ.png" /><figcaption>Click the play icon at the upper left hand side of the screen to run the simulator.</figcaption></figure><ul><li>When we click the “5” digit in the simulator, nothing happens! That’s because we haven’t yet taught the calculator app what to do when the button is touched.</li><li>The way we can make this button, which is in the <strong>View</strong>, do something is to connect it to our <strong>Controller. </strong>That is, when the button is touched, we want to invoke, or call a method in our controller. So how do we do that? We get the View and the Controller on the screen at the same time.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*7ZMCmKWIa_YzOSc3PxMFmA.png" /><figcaption>Click the Assistant editor to get the View, and Controller on the screen.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hFAo9n9jxyiTBTIm97KZgw.png" /><figcaption>Hook up the button to call a method in the controller by holding down control, and drag into the code. How magical!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*oVNQO7HuNOVIDCjvNobPzQ.png" /></figure><ul><li>Once you make the connection, you have two options (Outlet, or Action) to indicate what kind of connection you want to make between the user interface element and the <em>Controller</em>. In our case, we’ll choose Action because it is used for allowing something that happens in the UI (some action) to invoke a method in the <em>Controller</em>.</li><li>The name of this method will be “touchDigit”. One might need to change the generic type <em>AnyObject</em> to type <em>UIButton</em>. Note that this method takes arguments. In this case the sender is the argument which will prove useful because in the case of a calculator, we want each digit pressed to be able to tell us what it is.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*0k7S_kEgjq234VJZSHw9jA.png" /></figure><ul><li>This action will print “touchDigit” every time we click on the button. This will appear in the console. Note that to the left of the console is the debugger.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WsaaLzDTxxcXQ_RJcky-0w.png" /><figcaption>clicking the button twice prints touchDigit twice in the console.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*NAI6y2fejcRXY1feXJdTrQ.png" /><figcaption>Toggles the navigator, debug area, and utilities respectively.</figcaption></figure><ul><li>We can copy and paste the original button to make the entire number pad of the calculator.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mFEIERLOuyIXhyGI-LiPpQ.png" /></figure><ul><li>Each of the buttons are sending the touchDigit message. What we really want though, is to know which particular button is sending the touchDigit message. Let’s take a look through the Apple Developer documentation on <em>UIButtons</em>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WqI3HrK37_KVyZtRSYGzLg.png" /><figcaption>perusal of the documentation on UIButton leads to currentTitle as a property of relevance</figcaption></figure><ul><li><em>currentTitle</em> isn’t a method. It’s a property. Otherwise it would’ve started with the <em>func</em> keyword. It is of type String?. The <em>{ get }</em> is basically saying that we can never set the <em>currentTitle</em> property, we can only get it. Thus, it’s read-only.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pO20rNix9xuYZO5bjvOJOA.png" /></figure><ul><li>We’re storing the button’s <em>currentTitle</em> property in some local variable, digit. The syntax <em>\( )</em> in the print statement is called <em>String Interpolation</em>. It evaluates whatever is within the parentheses and converts it to a <em>String</em>, <strong>if possible</strong>. We do have a warning though! Let’s click on it to see what that’s about.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*CS1CJowP1b9ieazydmqeOg.png" /></figure><ul><li>Any time you declare a local variable or property that never changes after it has been initialized, always use <strong>let</strong> instead of <strong>var. Why do this?</strong></li><li>There are two main reasons to use <em>let</em> instead of <em>var</em>. Firstly, it’s easier for others reading your code to know that the variable never changes, and is as such a constant. Secondly, if the thing you declared with <em>let</em> was an <em>array</em> or a <em>dictionary</em>, that <em>dictionary</em> or <em>array</em> would be <strong>read-only.</strong></li></ul><h4>Run the simulator…</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*A2FxGSh0IWLPEino0Bw7MA.png" /><figcaption>Changed <strong>var</strong> to<strong> let</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*b5NWgYFH8ljloEuBKhikEQ.png" /><figcaption>touched the buttons 4, 5, and 6 to get the results above</figcaption></figure><ul><li>Hmm what’s this <strong>Optional</strong> in our output? Ok take a deep breath because <em>Optionals</em> are very important in Swift, and ubiquitous throughout the entire iOS API.</li><li>In Swift, there is a type called <strong>Optional</strong>. Just like <strong>Int, Double</strong>, and <strong>Bool</strong>, it’s a type. This type can only have two values or states: <strong>Not Set</strong> and <strong>Set</strong>. <strong>Not Set</strong> is expressed in Swift with the keyword, <strong>nil</strong>. If the <em>Optional</em> is in the Set state then it can have an <em>associated value</em> which can be of any other type.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*aKDCwZYU7FWcXienn4zzXg.png" /></figure><ul><li>So what is the type of <em>currentTitle</em>. It’s an <em>Optional</em>, and its associated type is <em>String</em>. Why is it an <em>Optional</em>? Well, we might have a button that we haven’t given a title yet, so it needs to have the case for when it is <strong>Not Set. </strong>We want <em>digit</em> to be a <em>String</em>, and not an <em>Optional String</em>.</li><li>Why didn’t we declare <em>digit</em>, like so:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*Z3XWLAbeZg0dfqFn7wRl6g.png" /></figure><ul><li>That’s because Swift can infer the type of <em>sender.currentTitle, </em>and it’s bad coding style to do so explicitly when it can be inferred. This capability of Swift to infer our type will make our code much more compact.</li><li>So if the button title is <strong>Set, </strong>how do we get that actual associated value of String? We put an <strong>!</strong> in the end. The <strong>!</strong> unwraps the Optional to give us the associated value.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*w-k7SEdK4bntNH3OxoytEw.png" /></figure><h4>Question: Why does Swift have this Optional thing instead of say emptyString to mean a button without a title? Or for an Int maybe -1, or for a Pointer perhaps 0 memory address to indicate they aren’t set?</h4><h4>The main reason is that, for example, in Swift we don’t see the memory address of pointers to object, so we couldn’t have it be 0. If we wanted an Optional Int, would it be 0, -1, or Max_Int? We see then that Swift is trying to be consistent among all types so that we can tell which ones are Not Set.</h4><ul><li>What would happen is we tried to unwrap, using <strong>!</strong>, an Optional that was in the <strong>Not Set</strong> state? It would crash our program!</li><li>Don’t be apprehensive towards using <em>Optionals</em> because you think your programs would be crashing all the time. In fact, crashing your program can be a good thing! Finding bugs that crash your program because they weren’t set at an expected time before you ship your app to the customer is certainly helpful.</li></ul><h4>Run the simulator…</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*f8tJw4QyssCv0Er2a_sEyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*5d26r3zrtG7jvG1Hn2oXuw.png" /></figure><ul><li>We now have the desired result when we press the buttons 4, 5, 6.</li><li>This is all nice, and good, but what we really want is for our calculator to have a display such that when we press the digits they show up in our display. Let’s get to it. Drag a Label unto the canvas.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w2vGSIJWP04sso-zOadJxg.png" /><figcaption>Label is read only!</figcaption></figure><ul><li>We could make the Label have a font-size of 40, and make the text/digit right-aligned like most calculators. We can also change the background color, and color of the text to whatever we please.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5rnS3QiZ_jygZuGW770-rg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*PTmyLkLiOKxSDr5z8Jd89Q.png" /><figcaption>Background color is set to blue</figcaption></figure><ul><li>How about connecting this Label to our <em>Controller</em>? In this case it will be a bit different. This is not the case, like the buttons, where we wanted a touch on the button to invoke some method in the controller. This is the other way around. We want to talk to it, we want to put things in the display. In essence, we want communication to be from the <em>Controller</em> to the display.</li><li>Control drag from the display to the <em>Controller</em>. This time we’ll choose an Outlet. An Action is a method, but an Outlet is a property.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*AG9R-5pY9hyFZnmPpcsiWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZVI89cWqLRgzC5oiK8T2fA.png" /></figure><ul><li>Now for the tricky part. In Swift, we can put the type of a variable after the colon(:). What’s the type of display. That’s right, it’s <em>UILabel!</em>. Wait a minute though! Isn’t <strong>! </strong>reserved for unwrapping <em>Optionals</em>? Well, in fact <strong>! </strong>like <strong>? </strong>also means <em>Optional</em> when declaring the variables.</li><li>Let us investigate what the <strong>!</strong> really mean as an <em>Optional </em>by making it <em>UILabel?</em> instead.</li></ul><pre>@IBOutlet weak var display: UILabel?</pre><ul><li>Now that we have a display, we want to append to this display the numbers that we pressed. Change our Action to:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PWaHy1ZRzdbaBlG890sCdg.png" /></figure><ul><li>When we assign the value of <em>display.text</em> to the property <em>textCurrentlyInDisplay</em> we get an error. Because <em>display</em> is an <em>Optional</em>, we need to unwrap it, like so, <em>display!.text.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hndqTKApCub8tbApN5qqrw.png" /><figcaption>text is an Optional String</figcaption></figure><ul><li>When we hold down option and click on text, we see that <em>text</em> is a property on <em>UILabel</em> and is actually also an <em>Optional</em>. Why is that? Well the <em>UILabel</em> might not be set. Therefore, we need to unwrap the <em>text</em> as well.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*vvzu84YivOXDhnd0e-v2sw.png" /></figure><ul><li>We now just need to set the text in the display to whatever was already inside it with the new digit we press appended to it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-_yPotzl_pxONjwsT_-a-w.png" /><figcaption>Note that we can concatenate Strings in Swift by just using +</figcaption></figure><ul><li>Notice here that we are setting this <em>Optional</em> (text). If we wanted to <em>Not Set</em> it we can do:</li></ul><pre>display!.text = nil</pre><ul><li>This will just clear the display.</li></ul><h4>Run the simulator . . .</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_g1VGHtOrTkrlvO8GG4HDg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K76kKwNP7Hn3dmHSSVvT1Q.png" /><figcaption>Pressed the buttons 7, 8, 9</figcaption></figure><ul><li>It works! There is one issue though. That zero(0) at the end isn’t really how a calculator works. When pressing 7, 8, 9, the display should be 789. When typing a new number, that <strong>0 </strong>shouldn’t be there. We need a way to keep track as to whether we’re in the middle of typing a number. If we are , then we append, but if we’re not then just replace the display with the new number.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ryn6lWQGlEuR7l5DLdmQHw.png" /><figcaption>added property userIsInTheMiddleOfTyping</figcaption></figure><ul><li>We now add a property <em>userIsInTheMiddleOfTyping</em>. That’s a long name, but quite descriptive, so don’t worry about creating long names as <em>XCode</em> will always escape complete. It makes sense that this property should be of type <em>Bool</em>.</li><li>As soon as you added that property though, an error occurred. It indicates that <em>Class ‘ViewController’ has no initializers</em>. The reason for this error is that: <strong>All properties in Swift must have an initial value.</strong></li><li>There are two ways to provide an initial value. One is by creating an <em>initializer</em>. We won’t be using that until a later date so we have to resort to the second way, which is to set the property to some value. We’ll set it to false since the user doesn’t start out typing in the middle of a number.</li></ul><pre>var userIsInTheMiddleOfTyping: Bool = false</pre><ul><li>One objection you may have then is that we didn’t initialize our Optionals like so:</li></ul><pre>@IBOutlet weak var display: UILabel? = nil</pre><ul><li>That’s because Optionals are treated specially. They are always automatically initialized to <em>Not Set</em>. That is, <em>nil</em>.</li><li>Do we really need to explicitly indicate that <em>userIsInTheMiddleOfTyping </em>is of type <em>Bool</em> though? No! It’s value <em>false</em> can only be a <em>Bool</em>, so Swift can infer its type.</li></ul><pre>var userIsInTheMiddleOfTyping = false</pre><h4>Code Logic Pseudocode</h4><pre> userIsInTheMiddleOfTyping = false</pre><pre> if userIsInTheMiddleOfTyping<br>     append the digit<br> else <br>     display the new digit</pre><pre> set userIsInTheMiddleOfTyping to true</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tt_vGtgfIbDmjsme0xDokw.png" /></figure><ul><li>Aren’t you tired of all these <strong>!</strong> points though? We have had to unwrap <em>display</em> each time when we know that it is pretty much always <em>set</em>. The only time the <em>display</em> isn’t S<em>et</em> is between the nanosecond it takes for the <em>display</em> to come on screen before iOS wired it up in our <em>Controller</em>. Once it’s wired up though, it’s <em>Set</em> forever. Certainly by the time users can start pressing the digits everything would be all connected, so it doesn’t make sense to keep unwrapping it when we know display will never be nil. The good news though, is that we don’t have to. We can now go back and change the display to be of type <em>UILabel!</em> like it once was. Any time we use an <strong>!</strong> when we declare an <em>Optional</em> it’s saying that anyone can use it because it will be implicitly unwrapped. Thus, by using the <strong>!</strong>, we make <em>display</em> an <strong>Implicitly Unwrapped Optional</strong>.</li></ul><pre>@IBOutlet weak var display: UILabel!</pre><ul><li>We can now get rid of all the other <strong>!</strong> after display.</li></ul><h4>Run the simulator . . .</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T-yD-pAPDwPVS7SHrejw4Q.png" /><figcaption>Pressed buttons 7, 8, 9, 5, 4, 5</figcaption></figure><p>Voila! Looks like we are on our way. The keyboard is functional.</p><ul><li>Add a new button π to the calculator by copying one of the previous buttons. This button will be an operation that displays π in the display. (Hold down <strong>alt + p</strong> to get the π symbol)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tQsYxiVbmMQfquDsSVS9ww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IJr4-13IPLUM-veCK00RKQ.png" /></figure><ul><li>Since we will have all our operations invoke this <em>performOperation</em> Action we’ll need to know what type of operation the button wants:</li></ul><pre>let mathematicalSymbol = sender.currentTitle! </pre><ul><li>Notice that because we want the <em>String</em>, we need to unwrap the <em>currentTitle</em>. What if there was no <em>currentTitle</em>, and that instead of crashing we just wanted to ignore it. We’ll basically just want to unwrap only if the <em>currentTitle</em> was <em>set</em>.</li></ul><pre>if let mathematicalSymbol = sender.currentTitle {</pre><pre>}</pre><ul><li>The above reads as if I can <em>let</em> my <em>mathematicalSymbol</em> equals the sender’s <em>currentTitle </em>then do something. This is the safe way to unwrap <em>Optionals</em>.</li><li>If the symbol is π then update the <em>display</em> with it:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v1i6OiEo-lGus2hKqkj95w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*AKiFt5o6OWIVBHz0XqIwbA.png" /></figure><ul><li>We get an error because M_PI is of type <em>Double</em>. It is the value of π. Our <em>display.text </em>is looking for a <em>String</em>. To get rid of the error we need to convert this <em>Double</em> value to a <em>String.</em></li><li>To do this conversion we just need to put the name of the Class with parentheses, then inside these parentheses put anything the Class will allow you to create one of itself with:</li><li>In our case since we want a <em>String</em> it’ll be:</li></ul><pre>display.text = String(M_PI)</pre><h4>Run the simulator . . .</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*18eYQ4J_hjzJiKR3fG0wtQ.png" /><figcaption>Pressed 8, 5, 4, 9 then π</figcaption></figure><ul><li>When we press π our display isn’t fitting all the digits.</li></ul><p>We can solve this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4GpTdvrv4BG0M9fhIVb4qw.png" /><figcaption>Change the minimum font size of the display label to 9</figcaption></figure><ul><li>We do have another problem it seems though! For some reason, when we press π, it appends π to the end. Here’s the issue. Because we created the π button by copying and pasting the number buttons, our π button is invoking two methods. It’s invoking the <em>performOperation</em> method, but it is also invoking the <em>touchDigit</em> method in our <em>Controller</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c1O-nR9RgCxtyAP0-lwY2g.png" /><figcaption>Click the x next to the touchDigit: to delete that connection</figcaption></figure><ul><li>Right click on the π button to see all the connections to it. We can confirm that it is invoking both methods when touched. Delete the touchDigit connection.</li><li>Whew! There is another problem. After pressing π and then another number button, it was assuming that we were in the middle of typing a number and appending those digits to the end of the π value. We can solve this by just ensuring that when we add an operation, we are not in the middle of typing a number.</li></ul><h4>Run the simulator . . .</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VcemAheYX9waOEMjHeHMxA.png" /></figure><h4>Well we now have a decently functional calculator with just one operation!</h4><h3>To be continued . . .</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=805950e1d006" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>