Swift

The Swift 2.0 Defer Keyword

Couldn't think of a suitable image, so here is a kitten on a computer.At WWDC 2015, Apple announced some substantial updates to the Swift Programming Language for version 2.0. Since its announcement, Swift has been undergoing a lot of updates. In fact, version 1.2 of the language had been released in April 2015 and by June we had the first preview of 2.0.

I decided to blog about some of the changes to the language that really caught my attention. The one that I like the most is the “defer” keyword. In .Net (and other languages), we have this concept of try/finally. Sometimes you can include a catch in there, but it isn’t required. The idea is that after the code executes in the try portion, the code in finally is guaranteed to execute. That’s the perfect place to make sure that you’ve disposed of objects or otherwise cleaned up after yourself. Pretty much every tutorial that I’ve ever seen in .Net has something like this:

try 
{ 
  connection = new SqlConnection(connectionString); 
  connection.Open(); 
  // Do Some Stuff
} 
finally 
{ 
  connection.Dispose(); 
} 

Sharp .Netters might point out that coding a “using” statement accomplishes essentially the same thing with anything that implements IDisposable, but I’m just trying to demonstrate a point 😉

There are a few problems with this try/finally style of coding, however. First, what tends to happen is that developers wrap large blocks of code in try blocks. The problem with that is that you don’t know what actually exists by the time you get to the finally. Maybe you’ve returned early from the method, or maybe an exception was thrown. Now, you’ve got to litter your entire finally block with “if this exists, set it to null” or “if this is open, close it” kind of stuff. That’s where “defer” comes in. Let’s take a look at some code that I ran in an Xcode 7 Beta 2 Playground:

class Foo {
    var Bar : String = ""
    var Baz : Int = 0
}

func showOffDefer() {
    var originalFoo: Foo?
    
    defer {
        print ("Bar was \(originalFoo!.Bar)")
        originalFoo = nil
        print ("Now it is \(originalFoo?.Bar)")
    }
    
    originalFoo = Foo()
    originalFoo!.Bar = "Lorem Ipsum"
    originalFoo!.Baz = 7

    print("We are doing other work")
}

showOffDefer()

Remember, the defer block isn’t called until the function is exited. So, what is written to the console is:

We are doing other work
Bar was Lorem Ipsum
Now it is nil

Do you see the power in that? Now, after I declare an object, I can write a deferred block and it is guaranteed to execute when the function exits. That can be any number of early return statements, that can be because of an exception, or it can be because the function just ran out of code and returned automatically (like mine here). These defer blocks are also managed like a stack, so the most recent defer statements are run first. Let’s see that in action:

class Foo {
    var Bar : String = ""
    var Baz : Int = 0
}

func showOffDefer() {
    var originalFoo: Foo?
    
    defer {
        print ("Original Foo's Bar was \(originalFoo!.Bar)")
        originalFoo = nil
        print ("Now it is \(originalFoo?.Bar)")
    }
    
    originalFoo = Foo()
    originalFoo!.Bar = "Lorem Ipsum"
    originalFoo!.Baz = 7

    print("We are doing other work")
    
    var newFoo: Foo?
    
    defer {
        print ("New Foo's Bar was \(newFoo!.Bar)")
        newFoo = nil
        print("Now it is \(newFoo?.Bar)")
    }
    
    newFoo = Foo()
    newFoo!.Bar = "Monkeys"
    newFoo!.Baz = 42
    
    print("We are doing even more work")
}

showOffDefer()

This gives us

We are doing other work
We are doing even more work
New Foo's Bar was Monkeys
Now it is nil
Original Foo's Bar was Lorem Ipsum
Now it is nil

Hopefully, that example helps make some sense of it. So what did we get? First of all, we got our two print statements that we were doing other work and then even more work showing that the entirety of the function executes before any defer blocks are called. But then it executes newFoo’s defer block first, finishing with originalFoo’s block last.

That seems pretty awesome to me. I realize that Swift isn’t starting anything terribly new here. The Go Programming Language already had this exact concept. That doesn’t mean that it isn’t a good idea.

Swift was created from the very beginning to be a “safe” language and I think defer blocks accomplish this in a few ways. First of all, it ensures that code gets executed. Secondly, it makes sure that only appropriate code is executed (it won’t try to cleanup for objects not yet created). Thirdly, it keeps the cleanup right near the declaration, so readability and discoverability is improved. Why is that safe? If code is easy to read and understand, and the places for modification are well-known and well-understood, then the code is going to be higher quality.

I’m excited for what Swift 2.0 is bringing to the table.

Podcasts

Podcast Episode 37 – On Remote Working

Remote WorkerEarlier this month, I saw a tweet that kind of got me fired up. It was pushing the same tired arguments about why companies that don’t allow remote working are backwards and dumb. Everyone knows the benefits for the developer in a remote working situation and most people know how having a distributed force can help the company. But, can you turn around and see things from the point of view of companies that don’t allow remote workers? In this podcast, I do just that.

Links Mentioned in this Show:

The tweet that got me started

Andy Adams in Episode 32

Hanselman’s Latest Remote Working Post

What to do when you’re the dumbest person in the room

You can also subscribe to the podcast at any of these places:
iTunes Link RSS Feed

Thanks to all the people who listen, and a special thanks to those who have rated me. I really appreciate it.

The episodes have been archived. Click Here to see the archive page.

Swift

What Happens When You Copy a Swift Dictionary?

DictionaryToday, I was listening to Episode 61 of the iOhYes Podcast (Podcast Since Removed), titled “Not Enough Words”.

This was the second show in a row talking about the Swift Programming Language. As part of the discussion, they talked about classes and structs in the language. During the discussion, it came up that in Swift, a Dictionary is a value type. That means if you assign a dictionary variable to another variable, it makes a copy. If you do that with a normal object, both variables just hold a pointer to the same spot in memory. If you change one, you change them both.

Well, the question came up that was basically, “If you have a dictionary full of objects and you assign it to another variable, will the objects be copied or referenced?”. The hosts could guess, but didn’t really know. I thought that it would be fun to try to find out. To do so, I wrote the following code in a Swift Playground in Xcode.

Here are the respective outputs:

Are originalFoo and referencedFoo the same object? true
Are originalFoo and anotherFoo the same object? false
Are referencedFoo and anotherFoo the same object? false

Are the values for first keys in the two dictionaries the same object? true
Are the values for second keys in the two dictionaries the same object? true
Is the value of the first key in the original dictionary the same object as the value of the second key in the copied dictionary? false

So, you can see that a dictionary struct is created, but it is just populated with references to the exact same Swift objects that were in the original dictionary. Playgrounds are pretty useful for just trying out code and testing these kinds of things. This is what I always used LINQPad for in .Net and I’m glad that this is available to us in Xcode.

Business of Software

Podcast Episode 36 – Developers vs PMs

Conflict, From http://info.profilesinternational.com/Portals/63683/images/Fotolia_3001454_Subscription_L-resized-600.jpgRecently, I found two “open letters” on the Internet. Episode 36 has me examining their contents and pointing out where I find fault with each. The letter that started it all was from a PM and was aimed at telling developers how to do their job. The rebuttal, from a Developer to a PM, was written to explain how the PM was wrong and how they should do their job. There is actually plenty of wrongdoing in both letters and we’ll take a look at that with the aim of behaving better and having better attitudes in the workplace.


Links Mentioned in this Show:
The Letter from the PM to the Dev

The Letter from the Dev to the PM

Fired

You can also subscribe to the podcast at any of these places:
iTunes Link RSS Feed

Thanks to all the people who listen, and a special thanks to those who have rated me. I really appreciate it.

The episodes have been archived. Click Here to see the archive page.

iOS

Our First WatchKit App – WatchCounter

In my last podcast episode, I talked about the Apple Watch Event and also a bit about what developing for the watch is like. WatchKit isn’t something that you can just create as a standalone application. Every WatchKit application must have a phone application. No processing happens on the watch, it is just a “dumb screen” for the application on the phone. So even if the entirety of what you are building is for the watch, the phone component must still be installed. The phone component is the “brains of the operation”.

Here is a diagram of WatchKit architecture from Apple
WatchKit Architecture from Apple, originally here: https://developer.apple.com/library/prerelease/ios/documentation/General/Conceptual/WatchKitProgrammingGuide/Art/app_communication_2x.png

And, here is one that I created to expound on it a little bit:
WatchKit Architecture

Let’s walk through making a very simple application. The source for this application is available on GitHub, or you can follow along.

First, we need to make a phone application. You see that WatchKit isn’t any of our options, so I’m choosing to make a Single View application.
You cannot File->New WatchKit” title=”You cannot File->New WatchKit” /></p>
<p>Next, I name it WatchCounter, make sure the language is Swift and the device is the iPhone and click Next.<br />
<img decoding=

At this point, we just have a standard iOS application and XCode appears as it always does.
Xcode before adding WatchKit

With the project selected in the explorer pane, make sure that your Target window is visible. If not, click this button to show it.
Show Target Drawer in XCode

Next, click the plus sign indicated here to bring up the Add Target window.
Xcode Add Target

We are going to choose an Apple Watch -> WatchKit App Target Template
WatchKit Target

For the options, we are just making a simple application, so leave most of the defaults. We are going to make sure that the checkboxes are cleared next to “Include Notification Scene” and “Include Glance Screen”. If you forget, it won’t be the end of the world. Our Watch Storyboard will just be a little cluttered. Because we wouldn’t be using those screens for this sample, they wouldn’t affect what we’re doing right now.
Xcode WatchKit Target Options

After you are done and click “Finish”, you are presented with this dialog (if you haven’t previously told it to never show again). Click “Activate” so we can continue.
Activate WatchKit App scheme

At this point, your project will be changed. Added to our project are two new folders: WatchCounter WatchKit Extension, and WatchCounter WatchKit App. For this project, the only thing we care about in the “App” folder is the Interface.storyboard and the only thing in the Extension folder we need is InterfaceController.swift.
Our new project structure with the WatchKit pieces added

If we click the storyboard, we’ll see this:
WatchKit Storyboard

Go to the controls (bottom right of Xcode by default) and find the Button and Label controls.
Button and Label Controls in Xcode

Drag the label onto the watch storyboard, followed by the button. The watch has a “flow” layout and will just stack the controls on top of each other with no overlap. You don’t have access to auto-layout or precise positioning. There are ways to group some controls horizontally, but for now we can be fine with stacking the controls.
Button and Label on the Storyboard

Select the label on the storyboard and go over to the properties window and change the values to the ones that you see here. The label’s text will change when the app starts up, so I just have some text in there so it is easy to see and select while we are working with it visually.
Setting the label's properties

Next, select the button on the storyboard and then set its properties.
Setting the button's properties

Now, if you click the assistant editor button while on the storyboard, it will bring up the code for the view controller side by side.
Assistant Editor

Click on the label to select it and then hold down control, click on the label, and drag over to the code window and let go right above the awakeWithContext method. A dialog will come up to create an outlet. Name it displayLabel and click to accept.

Next, control click the button and drag over to the code window right below the awakeWitContext method. It will again ask you to create an IBOutlet, but use the dropdown to change to an IBAction, name it buttonWasPressed and accept.

Next, type in the rest of the code shown here. All we are doing is creating a counter variable and then updating the label, keeping track of how many times we clicked. It should be fairly straightforward.

import WatchKit
import Foundation


class InterfaceController: WKInterfaceController {
    @IBOutlet var displayLabel: WKInterfaceLabel!
    var counter = 0

    override func awakeWithContext(context: AnyObject?) {
        super.awakeWithContext(context)
        
        // Configure interface objects here.
        updateMessage()
    }

    @IBAction func buttonWasPressed() {
        counter++;
        updateMessage()
    }
    
    func updateMessage() {
        var message = "Pressed:\(counter) time(s)"
        displayLabel.setText(message)
    }
}

Now, make sure that the WatchCounter WatchKit App is still the active schema and you are targeting the iPhone 6 simulator.
Run the application

When you run it, should should launch the phone and watch simulator and get a watch app up that runs like this:
WatchCounter Demo

That’s it. If you have any questions, let me know. Again, if you want to check this out and poke around rather than follow along, the code for this application is available on GitHub.