Getting into functional programming with Swift

This article examines two implementations of a logic puzzle written in Swift. The first example uses an imperative programming style, which is the style familiar to most iOS developers. Then we see the same small program written in a functional style, which is facilitated by several Swift language features.

Get the source code at https://github.com/ijoshsmith/break-a-dollar

The logic puzzle

A few days ago my friend mentioned over beers that there are 293 ways to break an American dollar. In other words, if someone hands you a one dollar bill, there are exactly 293 distinct coin combinations you can give them back to make it an equal exchange. The next day I started working out how to write code that counts the number of ways to break any amount of money. This article reviews two implementations of this logic puzzle.

If you are looking for an interesting puzzle to solve, consider putting this article aside until after you’ve written your own solution. I found this puzzle to be a very enjoyable challenge.

American coins

For readers unfamiliar with American coins, here is a quick overview of the coins and their values. Note, a one dollar bill and a one dollar coin are both worth 100 cents.

American coin values

Algorithm overview

After quite a bit of pondering, making odd hand gestures, and mumbling to myself about nickels and pennies, I eventually figured out a very simple way to solve this puzzle. I knew it would be easy to write a quick and dirty solution, but why settle for less? I wanted to find an elegant solution, so I kept attacking the problem from different angles until I found exactly that.

The key to the algorithm is to recursively subdivide the problem space. Determining how many ways you can break a dollar using all available types of coin is just a specific instance of the more general problem of determining how many ways you can break any amount of money using any subset of coins.

For example, suppose you wanted to find all possible ways to break a quarter. What this really means is finding all combinations of dimes, nickels, and pennies whose sum is 25 cents. If you were to start with a dime, then the problem becomes finding how many ways you can create 15 cents using dimes, nickels, and pennies. If you then add another dime, the problem is then to determine how many ways you can create 5 cents using nickels and pennies (of which there are only two: 1 nickel or 5 pennies).

Click here to read a more detailed review of the algorithm, in a text file included with the Xcode project.

Representing a coin

The algorithm I invented manipulates “coins.” A coin is simply an integer value that represents how many cents it is worth. I wrote an enum to define all available coin types, which also includes a static method that returns all coins in descending value order.

Imperative solution

A significant aspect of the imperative programming style is that variables change state. An imperative program is something like a micro-manager; it tells the computer exactly how to do its job. The following Swift code should look pretty familiar to most iOS developers, because Objective-C is an imperative language.

imperative

This code creates an array to hold the coins of smaller value than the current coin of interest. It appends items to the array in a loop, using a familiar loop-with-index construct. Then it uses a variable named ‘sum’ to count the number of ways to break some amount of money using an increasing number of the current coin of interest.

Code like this is the bread and butter of imperative programs. Now let’s venture into the weird world of functional programming to see how this same problem can be solved in a new way.

Functional solution

The functional programming style is heavy on functions and light on mutable state. By not having shared values change there are fewer ways for things to go wrong and less need for synchronization. Having functions as first-class entities in the language makes it possible to support higher-order functions, which allows functions to be composed out of other functions. iOS development has been heading in this direction for years with the introduction of blocks in Objective-C, and the host of APIs that started taking completion handler block arguments.

Here is my functional style solution:

This method’s second parameter is a Slice<Coin> instead of a Coin array because it does not need to copy coins into a new array. A “slice” of an array makes a portion of the array available, without creating a new array. The first line of the method creates a slice of the array, named ‘smallerCoins,’ which contains what functional programmers often call the array’s “tail.” The first item in a list is called the head, and the rest is called the tail. It’s worth noting that slicing an array will not cause an error if the specified range is out of bounds. In this example, when the array only contains one Coin (a Penny) the ‘smallerCoins’ slice is empty.

I created  ‘coin’ and ‘smallerCoins’ on the same line, using tuple syntax, because taking the head and tail of an array is arguably really just one task. Instead of writing separate lines of code to explain how to take the head, and then take the tail, we can instead be more descriptive and express the “take the head and tail” semantic in one fell swoop.

Instead of writing a loop and mutating a local variable to count the number of ways to break an amount of money, we can instead leverage the higher-order function named reduce. If you need a brief overview of what reduce is all about, check out my article about it here. This code reduces a list of integers, such as [0, 1, 2, 3, 4], where each value represents the number of a certain type of coin, such as 3 Quarters. The first argument passed to reduce is zero, which is the initial value of the sum parameter used by the closure/function that contains the reduction logic.

Parting thoughts

I’m excited by Swift’s support for a functional programming style. It can be a challenge to think in different ways, but in this case it’s worth the effort. A couple of years ago I taught myself enough Haskell to be dangerous. I was pleasantly surprised to find myself thinking of new ways to solve problems in my iOS development work because of my exposure to functional thinking.

Get the source code at https://github.com/ijoshsmith/break-a-dollar

Posted in Swift | Tagged , | 12 Comments

Maximizing the Preview Assistant Editor in Xcode 6

While working through a coding tutorial in the excellent iOS 8 by Tutorials book by the Ray Wenderlich crew, I learned about the new Preview Assistant Editor in Xcode 6. This is a feature that you can enable in an assistant editor while editing a view file (e.g. a storyboard or XIB). It shows what that view looks like on the ever-growing plethora of screen sizes, vastly reducing the time spent testing out UI changes on device simulators. It can also be used to see how a view will look when using strings from different languages, such as infamously long German words.

Rechtsschutzversicherungsgesellschaften!

Having this very useful feature relegated to an assistant editor is a shame. An assistant editor must share a window with its primary editor. I would prefer to open the preview in a new window, which would live on my second monitor, enabling me to see many different previews at the same time without needing to scroll around the assistant editor. I am not aware of a way to do this, but I found the next best thing. Here’s what my setup looks like:

The lefthand screen has the main Xcode window, in which I edit a view. The righthand screen has a maximized window with a nearly fullscreen preview of the view I’m editing on the left. As you can see in the photo, I can fit a preview of all four iPhone sizes into the screen at the same time. When I edit the view on the left, the changes are immediately reflected in the previews on the right. It’s pretty sweet!

Here’s how you can set this up…

  1. In the Project Navigator pane, single-click a storyboard/XIB file to open it in the main Xcode window.
  2. Now double-click that same file to open it in a new window.
  3. Move the new window to another monitor and maximize it.
  4. Click on the new window to make sure it has input focus, then type Option+Command+Enter to open an assistant editor in that window.
  5. In the assistant editor’s jump bar click on ‘Automatic‘ to open the drop-down menu (see the screenshot below if you don’t know what this means).
  6. Click on the ‘Preview‘ menu item to open the preview editor.
  7. Click and hold next to the assistant editor’s jump bar, then drag up or left (depending on which editor layout you prefer; vertical or horizontal), to maximize the preview’s screen real estate.

In case you didn’t understand the step involving the assistant editor’s jump bar, here’s a screenshot for reference:

Have fun!

Posted in iOS8 | Tagged , | 3 Comments

A Swift App that Calls JSON Web Services

In this article I introduce a small iOS 8 app written in Swift, named SwiftPlaces. I wrote the app in order to get more experience with the language and try out some new features in iOS 8, such as Adaptive Layout.

The source code is available on GitHub.
https://github.com/ijoshsmith/swift-places

SwiftPlaces allows the user to search for places by postal code and then view details about a place, including its current weather. It is a universal app, meaning it runs on the iPad…

…and on the iPhone…

iPhone

I made use of the new support in iOS 8 for using UISplitViewController on the iPhone, as well as the iPad. Due to the Adaptive Layout features in iOS 8 it was only necessary to create one storyboard to cover both device types, which is great news!

There are too many bits and pieces I find interesting to review here, so I suggest you download the code from GitHub and check it out in Xcode 6. Here are a few things to keep an eye out for…

Web services

The app calls two Web services from www.geonames.org, namely postalCodeSearchJSON and findNearByWeatherJSON. I wrote a simple class that fetches JSON from a server, named JSONService. Both of the Web services listed above are consumed via that class, which provides closure-based completion handling and the ability to specify which NSOperationQueue the closures run on. Here is an example of fetching a list of places with a given postal code, taken from SearchViewController.

postal-code-search

The success closure uses my custom marshal operator function (~>) to move between a background thread and the main thread, as explained here. This allows the app to create data model objects out of JSON, eliminate duplicate entities, and sort them by name on a background thread, leaving the main thread to only display those objects in a UITableView.

Note: I realize that some postal codes include letters, but it seems that the geonames Web service that I’m using doesn’t support them. I didn’t investigate the matter more than a few failed attempts at using Canadian postal codes. A happy side effect of this is the fun way I show an error message if the user tries to search for something other than a number. Check out UISearchBar+ErrorMessage.swift for details.

JSON processing

I decided to write the JSON-to-model conversion code in Objective-C, because Swift’s type safety is at odds with such an inherently “type unsafe” task. There has been quite a lot of activity and debate around JSON processing in Swift, but I found it was just plain easier to write that code in Objective-C. The following code is from Model Builders.m:

There is quite a bit more to explore in the project, so I encourage you to grab the code and check it out. If you know of a better way to use Swift or iOS 8 features than what I’m doing, please tell me about it in a comment.

Posted in iOS8, Swift | 8 Comments

Simplifying NSJSONSerialization in Swift

While writing a pet project app in Swift I put together this convenience function that simplifies converting an NSData into JSON objects via the NSJSONSerialization class. My JSONObjectWithData function adds a Swift-friendly API on top of the Foundation method of the same name. Here is a Gist showing how it works and how to use it.

Posted in Swift | Tagged , | 2 Comments

Nil-coalescing Operator in Swift

Update: As of Xcode 6 Beta 5 this article is obsolete. Swift now includes a nil coalescing operator (??). I am leaving this article on my blog for people who are curious about why such an operator exists or when to use it.

Working with optionals in Swift can lead to a lot of uninteresting code that unwraps a value and, if it is nil, uses a suitable default value. The problem is compounded by the fact that Swift requires if/else bodies to be enclosed with { braces }. This can cause what should be a simple, small piece of code to become tedious and verbose.

Consider a simple scenario where the user can type a number into a UITextField, which is then parsed from a String to an Int and stored in a data object. String.toInt() returns an Optional<Int> because not all strings can be parsed to an integer value. Regardless of this minor complication, there is no reason why performing such a task should require more than one line of code.

As seen in the last example above, I created a custom operator function, dubbed the nil-coalescing operator. That operator function evaluates to an optional’s value unless it is nil, in which case it evaluates to a fallback/default value. This is based on the null-coalescing operator in C#, which is formed by two adjacent question marks (??). Since Swift does not allow custom operator functions to include a question mark (correction: it does as of Xcode 6 Beta 5), I instead opted for two adjacent exclamation marks (!!). I think of it as “If the optional cannot be unwrapped (because it’s nil), then use this value instead.”

It’s important to note that the expression on the right-hand side of the operator does not execute unless the left-hand expression evaluates to nil. I accomplished that intuitive and expected behavior by making use of “auto-closures”; a relatively obscure Swift feature that allows you to create closures without using { braces }.

Here is a GitHub gist that shows the nil-coalescing operator definition and a few use cases.

Notice that the second to last example does not cause the getDefaultNumber() function to execute, but the last example does because it’s optional value is nil.


I’d like to thank my friend Jordan Nolan for bringing this point up and nudging me to work out a solution.
Posted in Swift | Tagged , | 21 Comments

Custom Threading Operator in Swift

The Swift language supports custom operator functions, similar to operator overloading in C++. This kind of language feature has been known to enable overly “enthusiastic” developers to create a quagmire of unreadable code, which is why I was surprised to see it included in Swift. However, when used with careful consideration and restraint, defining new operators can yield elegant and expressive code with minimal cognitive friction for its readers. In this article I show how to define an operator that simplifies thread marshaling, in particular the transfer of execution from a background thread to the main thread of an iOS app.

The code reviewed in this article is available on Github.
https://github.com/ijoshsmith/swift-threading

This code was compiled and tested against Xcode 6 Beta 5.

Demonstration

The sample project on Github uses a custom operator function in the ViewController.swift file. After the user taps a button two anonymous functions execute on a background thread. When a function completes on the background thread an associated function (i.e. closure) executes on the main thread.

When this code executes it logs:

[back] hello
[back] adding...
[main] goodbye
[main] sum = 49995000

Note that the handleButton action method appears to join closures with a mysterious new ~> operator…

{ /* background code */ } ~> { /* main thread code */ };

Operator ~>

The Tilde-GreaterThan operator (hereafter known as the marshal operator) is not part of Swift proper. I invented it to express thread marshaling semantics. It executes the lefthand closure on a background thread and when that completes it executes the righthand closure on the main thread. This is a very common thing to do when writing iOS apps that don’t suck, but with Objective-C there was never a terse, streamlined way to express it. Swift to the rescue!

I wrote two versions of the marshal operator. Let’s examine the simple version first.

Since Swift does not contain a ~> operator it is necessary to declare its existence, which is the first line of code seen after importing Foundation. The operator function is declared as infix because the ~> appears between two closures. This makes sense if you think of the tilde (~) as representing a thread doing its work and then “pointing at” (>) the next closure to execute when it completes.

The next line of code is an implementation detail. That queue constant is bound to a serial GCD dispatch queue on which all background closures execute. I chose to make it serial instead of concurrent because that simplifies the programming model, but feel free to make the queue concurrent if you prefer it that way.

The operator implementation is basic Grand Central Dispatch API usage, simply executing the background closure on a queue and, when it completes, marshaling back to the main thread’s queue to invoke a completion handler.

As seen previously, there is another version of the marshal operator that allows the background closure to return a result, which is passed to the main thread closure as a parameter. That operator function definition is very similar to the one seen above.

Other ideas

This code is just a starting point. There are many similarly useful versions of the marshal operator just waiting to be written. For example, you might have an array of closures on the lefthand side that all must complete before the main thread closure executes, which could make use of a dispatch group to manage completion handling. Or perhaps an operator that chains together multiple background closures and ends with a main thread closure. The possibilities are endless. Just make sure you don’t go overboard with it!

 

Posted in Swift | Tagged , , | 16 Comments

Understanding Swift’s reduce Method

Swift’s API includes many functions and instance methods that reflect its functional programming heritage. A prime example is called reduce.  You can reduce a collection of values down to just one value, such as calculating the sum of every person’s age in an array of Person objects. Using reduce eliminates the need for writing many loops in a program. Here is an annotated code listing that shows a loop and the equivalent usage of reduce to add together the age of every person in an array.

There are three matching parts between the two code snippets. The green box in both snippets shows how an initial value is defined, in this case zero. The yellow underline shows how each approach iterates the array of Person objects. The red underline is where the sum is accumulated. In the reduce code, the first closure argument ($0) is the running total, which starts at zero, and the second parameter ($1) references a Person object in the people array.

Posted in Swift | Tagged , | 7 Comments