Rick Rolled & Swift 2

There was a nice thunderstorm moving through my area on the night of the WWDC 15 keynote. That or the possibility that Apple was getting a lot of requests for the stream gave me many pauses. Usually they were timed to perfectly align with a good line by whoever was speaking at the time. During the demonstration of Safari for El Capitan, there was a cleverly placed “Rick Roll” to demonstrate muting the audio of a tab. I hope Apple realizes the gravity of the situation. At any rate, this was the clue to go to the Apple Developer Site and see what was new there.

There is a lot. Rather than enumerate the changes, I’ll just point to them. https://developer.apple.com/support/transition/ . I think this will make things easier. I also expect that people will now be very happy that they don’t have to pay for a membership to test their iOS apps on a device. This is a huge improvement. I’m sure I will be enjoying the upgrade. I haven’t read the new agreements yet. I tend to click through those things. But they are in my downloads folder.

What the big news is for me is Xcode 7. Finally there is exception handling in Swift. Except there is no finally. Damn I’m bad with jokes. Anyway, I’ve updated a project I’m working on to use the new Swift 2 syntax in Xcode 7. So far, the changes are not shocking because I’m not very far along with it.

So. Exception handeling. I was rather hoping for a Java style syntax which looks like this:

try {
    // stuff that may throw an exception
}
catch exception_type {
    // handle exception
}
catch another_exception_type {
    // handle exception
}
...
catch all {
    // handle lost cause
}
finally {
    // any cleanup code that needs to execute regardless
}

Presumably any stack unwinding that goes on will be in the thread that the exception is tried from (as opposed to stuff in the try clause executing code on another thread). Dancing around in threads makes things more interesting but is manageable. Objective-C has @try/@catch/@finally that will work with C++.

The throws/throw declarations and syntax appear to be sensible enough for either the above try/catch/finally arrangement and the one that Swift went with which is sort of like C++ except with an extra word (copied from the new Swift Reference):

do {
    try vend(itemNamed: "Candy Bar")
    // Enjoy delicious snack
} catch VendingMachineError.InvalidSelection {
    print("Invalid Selection.")
} catch VendingMachineError.OutOfStock {
    print("Out of Stock.")
} catch VendingMachineError.InsufficientFunds(let amountRequired) {
    print("Insufficient funds. Please insert an additional $\(amountRequired).")
}

It is worth mentioning that there is a defer clause available in the Specifying Clean-Up Actions section of the language reference.

You use a defer statement to execute a set of statements just before code execution leaves the current block of code. This lets you do any necessary cleanup that should be performed regardless of whether an error occurred. Examples include closing any open file descriptors and freeing any manually allocated memory.

defer statement defers execution until the current scope is exited. It consists of the deferkeyword and the statements to be executed later. The deferred statements may not contain any code that would transfer control out of the statements, such as a break or a returnstatement, or by throwing an error. Deferred actions are executed in reverse order of how they are specified—that is, the code in the first defer statement executes after code in the second, and so on.

The example given is:

func processFile(filename: String) throws {
    if exists(filename) {
        let file = open(filename)
        defer {
            close(file)
        }
        while let line = try file.readline() {
            /* Work with the file. */
        }
        // close(file) is called here, at the end of the scope.
    }
}

The above example uses a defer statement to ensure that the open(_:) function has a corresponding call to close(_:). This call is executed regardless of whether an error is thrown.

This may actually be better. You can chain the catches on type thrown. You can also prevent error propagation using try! instead of the regular try.

Since functions are proper types (AKA closures), this will avoid the thread dance as the code will be executed in the same lexical scope and thread. I’m being a little imprecise here, but I think you know what I mean. The functional style of the defer statement should keep the Swift programmers that use functional programming patterns a lot happy.

There is of course more to go through. Apple will be Open Sourcing Swift. That got a lot of applause. Linux will be supported which is brilliant because Swift would make a great programming language for server side applications. Linux is very popular on servers. The success of Swift on Linux will largely depend on the licensing model that Apple chooses. I expect Apple will want to retain control over the language itself rather than going through a traditional standards body. That is simply speculation on my part. But this has been the case with Java, C#, and rather a lot of other languages.

Starting a New Project

I’m moving on from QR Codes. They were fun to play with. And I also got to see some of the Core Graphics and Core Filter APIs. I’ve also decided that the CoreX stuff will need a thin abstraction layer for proper usage in Swift. For example, instead of using a CFDictionary, I want to use a native Swift dictionary.

My real worry with starting a new project is failure to complete. I have a real desire to get this one onto the App Store. If history is anything to go by, the odds of that are grim. Even so, I thought I would go ahead and blog about the process I am going through. Maybe someone will read it and give me ideas.

The new project I have in mind has been given the code name Leonardo. I actually hope to make that my product name in the App Store. It’s an OS X project that will be implemented in Swift. Obviously I will have to use AppKit and some of the Core Foundation and other frameworks. Hopefully I can structure the code so that the majority of it is straight up pure Swift. The reason to do this is I like Swift a heck of a lot more than I like Objective-C. I may even like it more than C.

So anyway. The first step in creating a new project is to have a mission statement, so to speak. It’s the goal of the project. It’s the thing that should not be lost sight of. I’m using TextEdit to write down my notes on the project. Here is the statement:

Mission Statement
Mission Statement

 

My notes include more than the mission statement of course. I have a strategy for achieving the goal, if I can indeed achieve it. A fundamental part of the strategy is the file format itself. It needs to contain the information acquired from the user via the UI. I’ve decided to use a bundle of JSON files. There will also be bitmaps stored in the bundle if they are imported into a project.

The first step in my project will be rather peripheral. I will be working on importing an SVG file, which is in XML, and converting it to JSON. I will also go the other way. On top of that, I will render the SVG file to PNG, JPEG, and PDF. I will also support SVG output. I’m not sure that SVG supports all the features I have in mind though. So SVG output may lose information or get really complex to create the data for rasterization.

XML is actually kind of complex to parse, unlike JSON. I will almost certainly use the NSXMLParser class to do the work for me. While I would love to do the job in pure Swift, it’s work that is not core to the project.

JSON may not be compact like a binary format, but the human readability is a great benefit. There are also wins in using JSON. To give a hint at what I mean here, Lisp is written as a Lisp data structure. Code is data. JSON is also well defined and has all the necessary elements in it to describe an image.

I do worry about recording all the user input taking up too much memory and creating very large files. I’ll have to do empirical testing to see if that will be the case. The part that will take up the most space will be the free hand drawing. Basic shapes that are part of SVG and Quartz Core won’t present such problems.

Another concern is processing the data fast enough to give the artist the impression that he is manipulating pixels rather than vector data. There is more work here than simply pushing pixels around. Again, I do not know if this will be a problem or not. Humans think in millisecond time scales at best. The CPU clock is clicking away at over a billion times per second. That’s about a million times faster. Also, the typical screen refresh rate is only 60Hz on an LCD display.

I should be able to beat that window.

This is actually an ambitious project I am taking on. There are already programs out there that allow users to do all sorts of fantastic drawings. I’m looking for a different approach that I hope will prove to be advantageous over traditional bitmap drawing programs.

Placing a logo image inside a QR Code

It is perhaps not all that well known that QR Codes were designed to be readable even when damaged. This is a clever feature built into the codes by using error correction to allow for smudges, wrinkles, and other damage to allow the QR Code to still be successfully scanned. This feature has the side effect of allowing the embedding of an image inside the QR Code, damaging it in the process, without seriously affecting the ability of the code to be scanned.

Some people have already taken advantage of this feature. You may have seen it before. I present to you a simple bit of Swift code that I wrote and ran from inside Xcode to create such a QR Code for a friend of mine to advertise his YouTube site. This code can be freely modified as required for your own use. I don’t see a need to copyright something so trivial.

[gist user=”DavidSteuber” id=”a6bf3df8c290ffc3839a”]

QR Code with logo
QR Code with logo

 

The reason for creating such a large code in this case is so that it can be printed onto a business card, sticker, or what have you without needing to scale up. Certainly there are other ways to do the job. In this case, I’m pretty much treating Swift as a scripting language for a one off job.

The advantage of this approach is that the method for creating such a QR Code using Quartz in an application is very obvious without having to create a bunch of boiler plate code for a proper app. The one downside is that it doesn’t show how you might do the same job in iOS and save the output to your photos. This script runs on OS X.