Adopting map() & reduce() in Swift

This is the third part in a series about Swift for Objective-C developers. Here are links to parts 1 & 2.

Part 1: Swift Optionals for the Objective-C Developer
Part 2: Variable Types in Swift for Objective-C Developers

Follow me on Twitter

Swift brings with it the ideologies of several programming paradigms. To Objective-C developers, the most obvious is likely to be a more functional style approach to solving problems. One of the fundamental aspects of functional programming is abstracting logic so that your code reads as a dictation of what it is doing, not how it is doing it. Unless performance becomes an issue, the implementation details of certain action are typically less important than the code being as declarative as possible.

One of the tools that makes this possible is the use of higher order functions, functions that take other functions and use them to perform transformations on a set of data. These include `map()`, `reduce()`, `filter()`, etc.

Swift includes these higher order functions and as you embrace the language itself it is also important that you begin to emprace them in order to make your code more idiomatic and easier to read and reason about.

The purpose of this article is show some common uses for these functions in your every day programming. We're going to fucus on `map()` and `reduce()` in particular, and explore some basic ideas as well as some more concrete examples. Let's dive in.

If you're a programmer it's very likely that at some point you've had to comma separate a list of strings.

Your first approach to solving this might include initializing an empty string, going through each item in the list, appending the current item to the string, and then adding the comma to separate it from the next item. It'd probably look something like this:

You knew what the output should be as soon as you read "comma separated" and yet, look how many steps it took me to explain it in words. Did any of that really expand on your understanding of what it is that we were doing in this code? No. Because the implementation details don't matter.

All we really want is to say that `commaSeparatedCoffees` is the result of some transformation on `coffees` and we want the code to be as succinct as that statement. This is a textbook use case for the `reduce()` function.

Note that Strings and other value types cannot be compared using `===` and `==` would cause issues if the same string appears in our list more than once. So to avoid this problem, we reduce over the result of `enumerate()` which returns an array of Tuples, where each entry in the array is the element of the original array as well as an Integer that corresponds to its index in the original array. This lets us correctly test whether the current object we're looking at is the last element in the array or not.

And we can refactor this logic into a generic `join()` function like the ones available in other languages.

Similarly, we can use reduce() to add up a list of numbers. This comes in handy quite often.

or more succinctly:

However, usually it's not just a raw list of numbers. The numbers are often encapsulated in another data type. We can use `map()` to extract the numbers from the objects, then `reduce()` to add them together. For example, let's find the average age of a bunch of people.

ometimes, you have an array of array's that contain a particular data type, but you want to collapse or flatten that into a 1D array consisting of all the objects.

Again we can refactor this into a generic method `flatten` that is implemented in terms of reduce()

Sometimes you want to find the unique values within a particular data set. For example, given a list of `Users` who each have a name and a list of things that they like, we want to obtain a list of all the unique likes between all the `Users`.

We can use a combination of `map()` and `reduce()` to achieve this.

  1. First we `map()` the users to their their likes, giving us an array of array's containg the likes.
  2. Next we flatten that list into a single array of likes using the flatten function we wrote earlier.
  3. Now we have our list, but it contains duplicated, so we ca apply `reduce()` to the list with an initial value of an empty set, and the reduce function will add each object to set.
  4. Because sets only contain unique objects, we end up with a unique list of likes.

Many times when implementing functionality such as form validation, you must combine the value of multiple booleans. `reduce()` is perfect for this.

We can even refactor this logic into a more generic function `combine()` that operates in terms of `reduce()`

In practice, you may have a list of options in your app and the state of each is represented by an `OptionState` object.

Given a list of `OptionState` objects, we can perform validation on the interactions with the list of options.

For example, are they all selected?

Or are any of them selected?

Here we apply `map()` first so the reduce() function works with only `Bools` and not `OptionState` objects like in the previous example.

From reading these examples, it should become more clear how using these functions can make your code easier to reason about. You begin declaring *what* you're doing and not *how* you're doing it. As you begin to write more and more code in this manner, additional uses for `map()` and  `reduce()` will come organically. Give it a shot!

If you enjoyed this post, you should follow me on Twitter.

Variable Types in Swift for Objective-C Developers

This introduction to generic types, protocols, and enums in Swift is part 2 of a series on Swift for Objective-C Developers. Check out part one about Optional Values here.

This post assumes you are familiar with the idea of generics, but either haven't used them in practice or have been burnt by other languages' (looking at you, C++) implementations and are reluctant to embrace them in Swift.

In Objective-C we have the almightly `id`, the basic representation of all object types in the language. We often use it as a catch-all when we don't necessarily know the type of an object we're going to be working with. Most often, it is used as the type for objects managed by a collection. Because we do not want to have a different class for every object type we want to contain in an array we use an array type that accepts objects of type `id`, so we can use any type we like. This is certainly better than having multiple classes such as NSStringArray, NSNumberArray, or NSIndexPathArray, etc. for each type we want to place in a container.

But, we can do even better!

There are very obvious flaws to this approach. It is important to remember that the Foundation collection classes (NSArray, NSDictionary, NSSet, etc) don't do this because it's the correct way, but rather because it is the best compromise given the limitations of the language.

There are three basic problems to this approach.

  1. Your code is incapable of being self-documenting. It is impossible to know what is being held inside of an NSArray instance simply by knowing that is an NSArray. If we had an NSStringArray class we know just by looking at it that there are instances of NSString being contained by the array. This is the type of self-documenting behavior we want.
  2. Type errors are introduced at runtime instead of compile time. Because methods such as `insertObject:` take an `id` instead of an object of a specific type, the compiler will never complain about the type of object you pass it, even if you pass an object of a type you did not intend. This means you may not catch the error until the code is running. When writing large apps with complicated code paths it is very common for these sorts of errors not be caught right away. And it can be particularly hairy when refactoring your code, especially when there are some infrequent code paths that you will inevitably forget about.
  3. It increases the amount of state in your application. When the compiler cannot dictate the correctness of the types in your code it becomes your responsibility. You must write code to modify the behavior of your logic based on the type of a particular object. Your application's flow becomes dependent on you maintaining the correctness of this logic without the help of the compiler to tell you when you screw up. Like runtime errors, this becomes a bigger issue while refactoring.

It isn't very difficult to understand why lacking type information is problematic. But how can we fix this? And how do generics fit into the equation?

Well, we fix these problems by giving our objects types. We simply have to compose types in order to create ones that are appropriate for our objects' requirements.

We can do this in Swift by utilizing generics and abstracting out a common interface for the objects we want to handle similarly.

As a concrete example, let's consider an online store app that displays a list of available products.

We could create a type for a Product itself.

But this can quickly become out of hand as you introduce different types of pruducts. Perhaps your store sells bikes and you'd like to have your user interface reflect the type of bike it is: a road bike, a mountain bike, a hybrid commuting bike, etc.

Now we have:

Your store also sells skateboards and you'd like to display the width of the deck, so you'll need to store that information as well.

You can see that this Product type is quickly becoming out of hand and becoming responsible for more information than the type was originally meant to represent.

The next obvious step is to create types for each of different products.

But now we're back where we started and we're duplicating information. Both of these types have a `name` and `price` property. Additionally, we can no longer store objects that may be of either type in one collection.

Both of these problems can be solved by parameterization of the common properties between these two products.

Doing this now gives us a new type, `Purchasable`, which we can use to refer to any object whose type implements the `Purchasable` protocol.

Using generics, we can now create an array whose type only allows objects that are `Purchasable`, in our application they can be either `Bike`s or `Skateboard`s.

As you can see, using generics we were able to create a whole new type, `[Purchasable]` (or with the alternate syntax: `Array<Purchasable>`), to represent an array of objects that are Purchasable. We immediately know looking at the type what it is and what we're holding inside of it. The Swift Array class abstracted out its logic using generics and now we get the perks of having specific array classes for a specific type (like the NSStringArray mentioned earlier) without having to write a new class manually for each type.

Additionally, this allows us to write code that restricts its own exposure to type information, limiting its responsibility to subset of the information that it actually cares about. For example, if we were to write a function that calculates the tax for a particular set of products, the function does not need to know anything about the product other than its price and therefore that is the only information the code using it should be exposed to. Because we have separated the `price` property into a protocol we can do so without our function caring whether the product is a Bike or a Skateboard.

Another type of problem we often use `id` to solve in Objective-C is the case where an object can be of multiple types and the instances aren't known at compile time. For example, consider a JSON object. Let's say we working with JSON objects that can be strings, integers, or booleans. We need a way to encapsulate all of these types so that we can write code that works generically with "JSON objects".

In Swift we can do this by creating a `JSONObject` type that is the composition of it's possible subtypes (String, Int, Bool) combined using an Enum.

Note that in Swift, the name of an Enum case cannot be the same as the type of its associated values, hence the more verbose names in this example.

This allows us to create objects whose type is `JSONObject`, but can represent specific values of other types without needing to explicity test which kind of value it is. More concretely, we are able to replace Objective-C code such as:

with Swift code like this:

This is better because `object` is adhering to a contract that can be checked by the compiler. It has a strict set of value types it can represent and the code reflects that exactly.

There are other implicit benefits to using method as well. For example, if you were to add or remove cases from the Enum, the compiler would alert you that you need to update the behavior of the switch statement to reflect the change. In the Objective-C code above, if you modify the behavior of the application such that the object can never be a number, you now have dead code in your application increasing its technical debt.

Swift's generics, in combination with protocols, allow a new level of abstract that was previously unavailable to Objective-C developers. The most obvious benefit is the introduction of typed collections as a first class citizen in the language but as we've seen above they play in an important role in making your own code safer and more correct. Similarly, Enums are a powerful feature when working with objects that can be of multiple types while maintaining an acceptable level of type safety.

Overall, these are very welcome additions to our programming repertoire.

If you enjoyed this post, follow me on Twitter.

Swift Optionals for the Objective-C Developer

This is Part 1 of a series of articles advocating Swift to the often stubborn Objective-C developer.

Some time has passed since WWDC 2014 and the reveal of the Swift programming language. The hype has settled and most of us have gotten on with our lives continuing to write our code in Objective-C, toying with Swift in our free time or using it for small modules within our production code. There have indeed been some early adopters writing new apps from scratch in the language, but I imagine that has more to do with the ability to announce the fact rather than any benefit to the programmer or business. After quite some fanfare, nothing has really changed.

I believe this is a good thing. Objective-C has been validated as a production-ready programming language for decades. Swift... not so much. It was necessary for Apple to release Swift when they did in order to garner the interest of the community and incorporate feedback. Creating a programming language is a process that spans years, and we're only in the very beginning stages. Swift is a language for 2016. This is made painfully obvious by the available tools and the state of the compiler itself. We're priviledged with a very mature toolset as Objective-C developers working with Clang & LLDB. But it wasn't very long ago that we were stuck with GCC and its less-than-perfect compiler errors, and that project was around for twenty years before it was fixed. We must be patient.

Along with patience, we should also be incredibly excited! Swift represents the future for Objective-C developers and that future looks quite bright. Swift may be new, but it is built on a solid foundation of programming paradigms that are much older than most Objective-C developers (certainly me, anyway!). It is a mix and match of features from the best languages that alone are not approachable enough for the demographic that Apple is trying to reach (for example, Haskell).

In the meantime, I'd like to show some of the more stubborn Objective-C developers the benefits they will receive from adopting Swift, be it now or later. To begin, let's discuss the concept of Optional Values, a new feature in Swift that is not available in Objective-C.

In Objective-C, objects are represented by pointers to their respective instances in memory, an implementation detail rooted in its history of being built on top of C. You will never see a statically initialized Objective-C object. That is, an object whose type is not a pointer. Indeed, even the common id type is essentially a typedef for void *.

Keeping that in mind it becomes clear that this can cause all sorts of problems in practice. The compiler and the language itself provide very little enforcement of where an object variable is pointing to because in the end, it's just another C pointer and C isn't designed to be restrictive of the operations you can perform on a pointer. To many, this is considered a feature and operations such as pointer arithmitic are first-class citizens in the C world. Indexing your C arrays using subscripting, myCString[42], is more or less shorthand for the pointer arithmitic equivalent: *(myCString+42).

Here's another example:

By supporting these sorts of operations, Objective-C sacrifices safety for flexibility. And in many cases, the flexibility is unnecessary. We don't need access to pointers more often than we do. Worse even, we must now keep track of the validity of our objects 100% of the time, even when we as programmers intend on an object to ever be in one state, because we have no way for the compiler to enforce this for us.

For example, let's take a look at one of the constructors of the NSAttributedString class.

From this declaration alone, we cannot be sure what would happen if we pass nil to either of the arguments of this function. In Objective-C, it's fairly common for this to happen unintentionally because their is no way to distinguish between an object pointer than can be nil and one that cannot.

And, as many of you probably are aware, this constructor in particular will crash should you pass it nil to the string parameter. That's not what we want at all!

Swift provides a solution to these sorts of issues in the form of Optional values. Optionals are a state machine that either represents a value, or nothing. This is fundamentally different from the concept of nil in Objective-C where it is just another location in memory, albeit an often invalid location. In Swift, optionals provide an abstraction that does not conflate the concept of values existing with low level details like memory addresses. They allow you to write code that mirrors your logic; "does this value exist?" not "is this pointer pointing to a valid location in memory and therefore can I consider this object to exist?". It's simpler.

This also differs from Objective-C because it does not allow nil messaging. In Objective-C, the runtime will happily accept nil as the receiver of a message, do nothing, and return 0. There are valid scenarios in which nil messaging is a useful feature but in general it causes more trouble than it's worth. An entire class of bugs can be attributed to Objective-C allowing nil messaging. You'll find many Objective-C developers championing nil messaging and claiming it's exclusion from Swift a step backwards. This is more of a side effect of years spent tailoring the solutions to their problems around the quirks of Objective-C than any inherit correctness in supporting nil messaging.

Swift's Optional values are somewhat similar to the adhoc Objective-C class, NSNull, whose purpose is denote the absense of a value, just like a Optional. However, not being a language feature and instead part of the Foundation framework, it is incredibly cumbersome and frustrating to use. NSNull is just another Objective-C object and by using it we're forced to now reason about two entirely different concepts of a null value, an unnecessary complication of our code. Victims of the NSJSONSerialization class can surely attest to this. In Swift, we promote the purpose of NSNull to a first-class language citizen.

Let's take a look at the syntax.

Optional value types are denoted by a Type, followed immediately by a question mark:

The combination of the two parts as a whole are a new type and can be used in a variable declaration just like any non-optional type.

in the case above, anIntOrNothing is an Optional value, that wraps an Int whose value is 42.

Here, anIntOrNothing does not have a value.

We can test to see if an Optional value has a value by comparing it to nil.

Or we can use the Conditional Let syntax to test if it has a value and, if it does, bind that value to a non-optional variable.

This can be considered syntatic sugar for the following:

The bang operator, ! is used to "unwrap" an Optional value. That is, if the Optional represents a value, then it will return the value. If the Optional value represents the absense of a value, doing so will throw an exception. It's important to always make sure an optional value is not nil before attempting to unwrap it. It is generally preferable to favor the conditional let syntax described above.

Optionals can also be chained using the ? operator. For example, the UIViewController property presentedViewController is of type UIViewController?. We can access its properties using optional chaining; the properties are automatically wrapped in an optional themselves in the process.

If we were to access the view property of the presentedViewController without optional chaining, first we need to get a valid reference to the view controller itself, if it exists. Then if it does, we can access its view.

With optional chaining, we can combine these into one step. However, notice the view types are different. In this case it returns a UIView wrapped in an optional.

This works for property setters as well. If both presentedViewController and its view property are valid references, then the view's background color would be set to white as expected. If either optional were nil, it would immediately stop at the first nil reference and nothing would happen. This can be seen as a bit of a safer, typed approach to nil messaging.

Swift also supports the concept of Implicitly Unwrapped Optionals. They're denoted with the following type annotation:

And in a variable declaration:

You should use an implicitly unwrapped optional when you cannot initialize the value of an optional when whoever owns the variable is created, but during it's use it will never, ever be nil. The latter is very important because attempting to use the variable without ever assigning it a value will throw an exception.

At first glance, the implicity unwrapped optional may seem to reject the entire purpose of an optional value, and in theory this is true.

In practice, as Mac OS X or iOS developers, the use of implicity unwrapped optionals was included as a necessity. When loading a nib file, the property references aren't set until after the view is loaded, which is no way coupled to when the instance of the owner class is initialized. If the @IBOutlet properties were not optionals, there would be no way to initialize them when the instance is created because the view has not been loaded yet. And if they were regular optionals, we'd have to unwrap them manually everytime we reference them, even though we intended on the connections to always be valid. Implicity unwrapped optionals are a convenience for cases such as these and in your day to day programming in Swift, this is the only time you should use them.

Here's a concrete example:

This also demonstrates an additional benefit of the implicity unwrapped optional: if your forget to make a connection in Interface Builder your app will crash instantly when trying to access one of the unititialized outlets. Despite the nasty word "crash" this is really fantastic in comparison to Objective-C, where many of you have undoubtedly pulled your hair out trying to figure out why a label's text property silently refuses to change only to realize your forgot to connect the label to its respective property in IB. nil messaging is a nuisance.

In most other scenarios you should prefer that your instance variables be declared with let or private var and be passed as a parameter to an init constructor. This will come up often when declaring an optional delegate property in Swift.

Then you can use it like so:

This is preferable to declaring the instance variable as a public var and assigning it after the fact, as it guarantees the state and validity of the delegate property and ensures it cannot be changed without the controller knowing.

Last, one of the biggest benefits of supporting Optionals is much more straightforward and simple. So simple it can be easily overlooked.

By explicity typing your Optional values, you are implying that every single other non-optional type must always have a value and therefore be valid. Duh, you're thinking. But this is serious improvement in comparison to Objective-C and C. Because this implication is built into the language itself, the compiler is able to tell us when we're wrong and enforce this religiously.

Let's revisit the NSAttributedString example. In Swift, the declaration looks like this:

Using this declaration of the NSAttributedString constructor, we now must pass in a valid string. Passing nil or a String? (optional String type) will result in a compiler error and fail well before the runtime exception we would have gotten in Objective-C.

This is incredibly powerful. A large part of being a programmer is being able to maintain and reason about the state of your code at any given time. In Objective-C that includes having to reason about the validity of every single object in your code. In Swift, that facet is handled by the compiler, which has a far better memory than you do.

Swift's optional values absorb a significant amount of work that is required of every Objective-C programmer. And while the langauge itself isn't quite ready for production use, iOS and Mac developers should be excited about a future that includes such powerful features built into their primary language.

Continue on to Part Two: Variable Types in Swift for Objective-C Developers

If you enjoyed this post, follow me on Twitter.

Uploading Files to Amazon AWS S3 in the Background with AFNetworking 2.0

  Recently, a client asked me to make a change to an app that uploads image files to an S3 bucket so that the transfer happened in the background. The app was using AFNetworking 1.x and an outdated version of the Amazon AWS libraries. After updating those two libraries, I set out to find the best way to integrate the background data task features of NSURLSession with AFNetworking 2.0. Here's what I found.

First, you'll need to update your libraries to the correct versions. AFNetworking 2.0 introduces support for NSURLSession via AFURLSessionManager so you'll need to be using at least version 2.0. The AWS intregration code in this article depends on version 2.0 of the AWSiOSSDK. Using CocoaPods, your dependencies might look like this:

Next, we'll need to obtain a signed URL from the AWS SDK with which we can setup a data task. The AWS SDK exposes an API called `AWSS3GetPreSignedURLRequest` for this purpose. It's built using the Bolts Framework in order to support creating this URL asynchronously. We'll use the API like this:

Next we can write a method that takes the signed URL and creates a data task that uploads the file.

Finally, we can combine these two methods:

That's all there is to it. Still having trouble? Feel free to shoot me an email.

Really stuck? Or are you looking for a developer to create an app that has this sort of functionality?

I'm available for consulting & freelancing work as well.

Building RunSwift

This is an explanation of how I built RunSwift. I came up with the idea for RunSwift back in June, just after WWDC. I thought it would be very cool to be able to demo Apple’s new language without the hassle of downloading the Xcode Betas. Not only do you need a Mac but you also need to be a registered developer. There were many people that weren’t able to try the new hotness, which was unfortunate because Swift garnered interest from people in many techonology circles, not just Apple developers. Unfortunately, I was knee deep in building a huge feature in the Fitocracy app so I had to put the idea on the backburner.

Fast forward to the end of August and the new Playback Mode in Fitocracy had shipped (and was incredibly well received!) and I was a few days away from a vacation. I had recently decided to take on some freelance work and knew the best way to get my name out to as many prospects as possible was to build something interesting. So I took out my notes on RunSwift and got to work.

The first thing I had to do was pick my technologies. Obviously I was going to need a Mac and the Swift compiler to do the dirty work, so I setup a remote Mac Mini server with MacStadium and installed Xcode Beta on it. Immediately afterwards, I disabled all remote access to the machine besides SSH.

Next I had to think about how I was going to make the website itself. I decided early on that the web application would be separate from the build server because I didn’t want anyone to have direct access to the Mac Mini for security reasons. It is also rather expensive to host the Mac Mini server so if traffic increased enough that I would need to get a second server it would have exhausted the budget for this little project.

And indeed the night of the launch I did have to get a second server up and running to handle the traffic. Luckily, I chose Heroku as my hosting platform and this was incredibly easy; I just increased the amount of web dynos from one to two and everything ran smoothly.

I figured the web app itself could be pretty lightweight considering it wasn’t going to be doing much other than servering a few templates and relaying compilation requests to the build server.

I chose Sinatra to build the app because I’m most familiar with it and I enjoy working in Ruby. It also has a threaded mode that makes concurrent request processing very easy so I was confident it would be able to handle the compilation requests which would potentially take a few seconds to send and receive. I believe this was the right choice in the end as it led to virtually zero hiccups during a high traffic 24 hour period, successfully handling over 10,000 compiles.

The bulk of the web app was simply serving a few template and JavaScript files, and the small POST handler for compiling the source code. The handler requires an API key that is validated before relaying the code to the build server. This isn’t a particularly fancy system; the API keys were generated with uuidgen and are just there to give me an idea of where the requests were coming from. You can find the one used by the web app in the JavaScript files.

The rest of the app was built in JavaScript using jQuery. The text editor is the excellent Ace text editor and the HTML and CSS were written with the help of Bourbon Neat (the CSS is written in SCSS).

For the build server, I again used Sinatra in threaded mode. It also contains a small POST handler that validates an API key (a different one than is used by the frontend when talking to the web app; this API key is secret and used to ensure that only the webapp can talk to the build server) before processing the request. Once validated, the handler scans the code for a series of blacklisted APIs, such as “import” or “writeToFile”. The request is rejected if it contains any of these APIs. Next, code is prefixed with a few lines of Swift that are saved to a template file and loaded into memory when the build server starts. This template file contains some basic imports like NSLog, NSString, NSArray, NSDictionary, etc. The final Swift code is then saved to a temporary file whose path is passed to a bash script called run-swift. This script compiles and runs the Swift code. Both steps are wrapped by the timeout utility in coreutils to ensure they cannot take more than a few seconds or so. If everything goes well, the script exits with exit status 0. If the compile task fails, it exits with status 1, and if the any of the steps timeout it exits with status 2. This allows the build server to respond with some context around why the request failed.

The execution step of run-swift is delegated off to a second bash script called that takes the path to the executable. This file is responsible for running the Swift code in a sandbox by wrapping the call with sandbox-exec using the appropriate permissions. The permissions work like a whitelist. All system access is explicitly disabled, with only a few directories allowed for read access and the execution flag enabled for the Swift executable itself.

If the compile task succeeds, the build server returns the result as is to the web app which hands it off to the JavaScript where it is rendered in the page.

When the compile task fails, the compiler output is first cleaned up to remove the path to the temporary files used during the task, and then the result is returned with the appropriate error message.

I launched the website on Hacker News on a Saturday afternoon where it was very well received. The next morning, it was posted to Product Hunt and various other tech sites. Combined, this led to quite a lot of traffic for several days straight and the site never went down. It ran very smoothly and I’m proud of myself for building a system that was resilient enough to be able to handle the traffic.

In the end the app led to many inquiries about consulting work, one of which I signed within the next 48 hours. In total, two of the inquiries led to signed deals. It took 15 hours total to build RunSwift so I’m happy with that return on my investment and I believe it’ll lead to even more work in the future.

That’s pretty much it. RunSwift was a blast to build and I hope you found it and this write up useful!

Thanks for reading.


I had some free time over the last week so I built an online sandbox for playing with the Swift programming language in the browser. There is limited access to Foundation included, and you're not allowed to import any external libraries. You can find it here:

RunSwift was submitted to Hacker News and Product Hunt where it gathered a lot of interest. Someone asked how it was made and here is my reply:

I took some time off this week and built RunSwift from a hotel room down in Atlantic City! It's something I've been thinking of doing since I first started playing with the language but hadn't had the time. Swift is a big deal. It maintains a lot of the raw power of Objective-C while enforcing stricter standards on our code through a powerful type system. I think it'll lead to better code and better apps, and I wanted to let more people give it a try. Plus I needed to brush up on Ruby/Sass skills :)

The app itself is composed of a few parts, namely: 1) a user facing Sinatra app that's hosted on Heroku (which made it really easy to keep up with the traffic it saw last night). This is what you see when you go to the site. And 2) a backend Sinatra app (running via thin in threaded mode) that runs on a Mac server with a suite of bash scripts for validating, compiling, and running your code. Code is checked for a series of blacklisted APIs, prefixed with a template file that includes some select APIs from Foundation, compiled, and finally run via sandbox-exec. Each step has a timeout powered by the timeout function in coreutils. Finally, the results are relayed back to the frontend app and shown on screen.

It was super fun to build and I'm glad you guys think it's cool, too!

Getting Started with Sass for a Wordpress Theme

I'm currently in the process of updating the style of my blog, which is powered by Wordpress, using a custom theme I'm developing. As frontend web development is new to me, I set out to research different technologies and I decided to use Sass instead of vanilla CSS. At first, I had some trouble getting a nice, fluent Sass workflow with Wordpress. If I had trouble, I'm sure there are tons of other people who are struggling too and could use some help. Here are some (fairly opinionated) steps for styling your Wordpress theme with Sass.

  1. In the root of your Wordpress theme's folder, create a subfolder and name it `sass`.
  2. In `sass`, create a file called `style.sass` (or `style.scss` if you wish to use the CSS subset of Sass). This file should include the header information for your theme that you would normally add to the `style.css` file required for your Wordpress theme.
  3. When writing your Sass source code, use a separate file for each individual type of item you're styling, and you must prefix each file with an underscore.
    1. For example, you might have a `_single-post.sass`, `_page.sass`, etc.
    2. Why must you use have the underscore? When watching a directory for changes to its files, Sass will generate a CSS file each Sass source file that does not start with an underscore. These are called partials. They're for separating the concerns of our Sass source, and will be combined later on by the compiler.
  4. In `style.sass`, add an @import for each partial you've created. Each @import should omit both the underscore and the file extension. Here's an example:
  5. Great! All the files should be setup now. We just need the right magic on the command line for Sass to generate the `style.css` file needed for your Wordpress theme.
    1. Open a terminal, and change the current directory to the root of your Wordpress theme.
    2. Run the command `sass --watch sass/:.That's it.
    3. This works because the only file without an underscore in the `sass` directory is `style.scss/sass`, so it will only create a corresponding `style.css` in the current directory (the format for the --watch command with folders is `<folder to watch>:<output folder>`).
    4. Note: This will also regenerate your `style.css` when you change the content of your partials, since they are @imported. Magic.
  6. Now, just edit your styles and your `style.css` will be regenerated each time you make a change!


I hope you found this helpful!

P.S. Need a developer for a project? I'm available for freelance software development.

Symbolicating iOS 8 Crash Logs

Hiya! This page gets the most traffic of all the content on my site! Whoa!
I decided to try and help you all with this problem.

I've started writing an application for symbolicating crash logs.
Want to try it? You can download a beta here.

If you're having crash logs come in via iTunes Connect or another service and having trouble symbolicating them, you're not alone. I spent about an hour trying to coerce Xcode into showing me the location of a crash in my application code, but Xcode 5 is not able to symbolicate crashes from iOS 8 because its developer toolchain lacks the necessary symbol files. The solution is to use one of the Xcode 6 beta builds, which include the symbol files for iOS 8. I have Xcode 6 Beta 4 installed, and it doesn't have the Device Logs pane of the Devices window like Xcode 5 does, so you'll need to use `symbolicatecrash`, the script the powers resymbolication in Xcode.

  1. Gather your crash log and the dSYM file for your app.
  2. Open a terminal and navigate to where you put your crash log and dSYM file.
    • We'll call them `myapp.crash` and ``
  3. Run `sudo xcode-select --switch /Applications/`
    • Replace `` with whichever version you have installed.
  4. Finally, run:

DEVELOPER_DIR=`xcode-select -print-path` /Applications/ -o ./myapp-resymbolicated.crash ./myapp.crash ./

If everything went smoothly, you'll now have a file in the current directory named `myapp-resymbolicated.crash` that contains the resymbolicated crash report. That should be it!

Did you find this helpful? You should follow me on Twitter.

UIView with NIB loading and Auto Layout by Example

Added a couple repos to GitHub: Auto Layout by Example — an Xcode project that includes several views laid out via Auto Layout to demonstrate how to achieve some commonly sought after results.

UIView+LENibLoading — A category on UIView and an accompanying subclass of UIView for loading views from a nib.

Auto Layout has its quirks but it is definitely going to be a big part of our future as iOS developers so the easier we can make its use and the more familiar we get with it the better. With the likelihood of a new iPhone coming out with vastly different screen dimensions, hopefully this helps some people get going sooner than later :)

GitHub Header Implementation Switcher

I made a Google Chrome Extension for switching between header files and source/implementation files (for iOS: .h and .m, but also works with .mm, .c, and .cpp files) on using the keyboard shortcut Ctrl+Cmd+Up, like in Xcode. You can get the source here.

In Chrome, go to chrome://extensions, press "Load unpacked extension...", then select the folder to get it running. If I have time one day I'll package it for the Chrome store.

It's pretty simple. I'm not a Javascript guy so the code might not be perfect but it's quite useful.

Thoughts on Auto Layout

Over the past two weeks I've been working on an update to the Fitocracy application that involves a redesign of the Feed and Notifications interfaces. The previous version of these interfaces are built on top of Core Graphics, all of the drawing is done manually. At the time, these seemed like a good idea; we were still supporting earlier iOS version on earlier devices and there was some merit to architecting those systems that way. In 2014, we support only iOS 6+ and the majority of our users have devices that would benefit far more from GPU accelerated graphics. So for this new version of the feed I moved all the work back to UIKit and, eager to work with something new, I laid out the majority of my views with Auto Layout. As the bulk of the work is beginning to wind down, I've been reflecting on the experience. There are some obvious benefits to having moved the code to Auto Layout.

I think the biggest win overall was a significant decrease in lines of code that would have been dedicated to layout. As the Fitocracy app has gotten older, its codebase has also grown proportionally; it now includes a few hundred thousand lines of code, all of which I am responsible for maintaining. With that in mind, encouraging less new code and finding ways to deprecate old, unnecessary code has become increasingly important to me. Using Auto Layout saved me from writing hundreds of lines of code for the new views I introduced for the Feed updates and I'm very grateful for that.

In a related fashion, Auto Layout, in conjunction with updates to Xcode, has also made it much more pragmatic to strictly adhere to the MVC pattern. Of course, MVC is not perfect by any means, but modularity and standardization are important practices in software development. You don't have to believe in MVC, but you should believe in something. Apple has pushed MVC on iOS developers, but in the past they haven't done a very good job of making it easy to adhere to. In fact, they've arguably made it easier to break it. Layout code in view controllers is an unfortunately ubiquitous practice, one of which I've been guilty on many occasions, even though I know it is wrong. The alternative, creating countless UIView subclasses to manage a view hierarchy, presents a cost that is greater than the adverse effects of breaking MVC. This is especially true when the hierarchy is simple. If one of your overarching goals is to limit the size of your code base, it does not make sense to add two files and thirty lines of code for a new UIView subclass. With Auto Layout, I was able to mostly avoid writing an layout code at all, let alone any in my view controllers. That was pretty great.

Additionally, as of Xcode 5.1 (currently in beta), you can natively create XIBs for UITableViewCell subclasses. This was huge for me. Previously, I was creating my views for them separately in UIView subclasses and loading the XIBs manually and adding them to the table view, which was a mess and involved playing around with various combinations of translatesAutoresizingMaskIntoConstraints amongst the views until Auto Layout decided (seemingly randomly) that my layout was unambiguous. Because I reuse certain parts of the view, I still do have some of them loaded from separate XIBs and have to continue this practice for those views, but for the most part it has gotten significantly easier. The cells that weren't sharing any common views loaded from separate XIBs were a breeze to create and layout. I do however, wish, that Apple would add the ability to specify that UIView in one XIB is to be loaded from a separate file. I recall this being the case when doing Mac development years ago, and I'm curious why it was removed. However, now that XIBs are easily usable once again I imagine this will come in the near future.

So there were certainly several upsides to using Auto Layout for this project. But, of course, there were some aspects that made me want to rip my hair out.

Most notably, the UIView property translatesAutoresizingMaskinToConstraints quickly became my nemesis. The boolean flag, which has an default value of YES unless the view was loaded from a XIB, determines whether the layout engine should turn the autoresizingMask property into a set of NSLayoutConstraints and add them to the superview implicitly. At the surface, this makes some sense; it could potentially facilitate a graceful migration of legacy code whose layout utilizes springs and struts into the modern age. In theory they could peacefully coexist while all new code is moved to Auto Layout. In practice, the property is an absolute nightmare. It makes it incredibly hard to debug issues in your code. This is exacerbated by the fact that it is depended on by certain classes within UIKit, such as UITableViewCell. Additionally, in my experience it has different behaviors between iOS 6 and iOS 7. Indeed, I have recently written code that sets the property on UITableViewCell's contentView different depending on the version of the OS. I suspect I'll have to keep a close eye on this in the future to ensure it doesn't break with software updates.

Alongside this issue is the fact that debugging Auto Layout is a hellish experience. On OS X there is a NSWindow property for displaying constraints visually, so you can see the ambiguity. On iOS we are left with some console output telling you to check if translatesAutoresizingMaskinToConstraints has accidentally screwed up the layout and a list of the constraints that were unable to be satisfied. The list is in the Auto Layout Visual Format, with only the class name of a particular view and it's pointer address as identification. There are libraries that exist to make this process easier, though I haven't tried them yet. I suppose there is room for a Mac app that can render the NSLayoutConstraints visually, though, a la Spark Inspector or Reveal. I'd certainly pay for that.

Thanks for reading.