Swift

Software development never stands still. But if there’s one gravitational force that holds sway over the entire profession, it’s that abstraction increases over time. Progress is not linear—there have been periods of stagnation, great leaps forward, and plenty of setbacks—but the long-term trend is undeniable.

The first modern programs were written in machine language: sequences of numbers often written in binary or hexadecimal. Assembly language was a step up the abstraction ladder, representing data and instructions with symbols instead of the raw digits of machine code. Languages like Pascal and C divorced themselves from the details of any specific CPU’s instruction set, providing a hardware-agnostic interface for programmers. Later still, languages like Java and C# moved away from direct access to memory.

Apple has been around long enough to have spanned much of this history. Though the original Macintosh, with its industry-defining GUI, was a technical marvel in 1984, a large portion of its operating system was written in 68k assembly code. Apple’s preferred language for application development has been on a slightly bumpy road toward higher-level languages, moving from Pascal to C and C++, taking a detour into Java, and finally arriving at Objective-C.

Moving up the abstraction ladder does not mean the old, less-abstract languages disappear entirely. Small portions of OS X are still written in assembly code today. Larger portions are written in C and C++. The top-level frameworks that application developers use are mostly written in Objective-C. It’s a continuum, with ever-decreasing proportions of programmers and code at the lower levels. Ask a modern OS X or iOS developer to create a full-featured GUI application using only assembly language and expect to be laughed out of the room.

Programming languages and APIs have their own sort of inertia. Once a community and a powerful set of tools has built up around a language, it’s hard to make the next leap forward. This inertia was on my mind back in 2005 when I warned that Apple was in danger of falling behind the rest of the industry in terms of programming language abstraction, just as it had once famously—and nearly disastrously—fallen behind with its operating system, fumbling with the ill-fated Copland project for years with nothing to show for it.

It took the NeXT acquisition and the return of Steve Jobs to finally give Apple a modern operating system. What would it take to get Apple to move beyond Objective-C? If Apple didn’t start thinking about its next move soon, I worried that it could find itself in another Copland-like jam by 2010, at which point I assumed all its competitors would have higher-level programming languages.

The year 2010 came and went and Apple was still flying high, thanks partly to its success in the mobile market where its low-level language gave it a performance advantage over its smartphone competitors. I was appropriately chastened by my overly cautious timeline, but I nevertheless insisted that the problem remained. Apple needed to do something.

This opinion faced widespread—and predictable—opposition from many Apple developers, both inside and outside the company. But one very important person at Apple saw an opportunity to advance the state of the art and seized it. In July of 2010, coincidentally a month after my Copland 2010 revisited article was published, Chris Lattner, creator of Apple’s LLVM compiler infrastructure and then senior manager and architect in Apple’s Developer Tools Group, secretly began work on a new programming language.

Four years later, Lattner, now director of Apple’s Developer Tools Department, appeared on stage during the WWDC 2014 keynote and shocked thousands of assembled developers—and quite a few Apple employees—by introducing Apple’s new programming language for OS X and iOS: Swift.

Like the end of any good mystery, the announcement of Swift shed new light on past events. Synthesized properties, dot syntax, blocks, automatic reference counting, collection literals—all these additions to Objective-C over the years have, unbeknownst to us, traced the outline of a shape lurking just below the surface. In the case of ARC, it went far beyond appearances; the work was directly applicable to Swift.

I’m not going to take you on a comprehensive tour of Swift’s syntax or features. Apple has published The Swift Programming Language, a free e-book that describes the language in great detail. Swift has been changing rapidly since it was announced; the e-book has been revised four times already. Though Apple makes some application binary compatibility guarantees, it has explicitly promised not to maintain source compatibility as the language evolves.

What matters most about Swift is spelled out in the first chapter of The Swift Programming Language. Swift is intended to be “the first industrial-quality systems programming language that is as expressive and enjoyable as a scripting language. […] It’s designed to scale from ‘hello, world’ to an entire operating system.”

Perhaps this mission statement is so grandiose—so preposterous, even—that readers are inclined to gloss over it or dismiss it. But it’s the key to understanding the design of Swift.

Such great heights

One part of Swift’s mission is easy to understand: it must move Apple’s development platform to the next rung on the abstraction ladder; it must be a higher-level language than Objective-C. That means memory safety by default, ending the era when even the most routine code was one bad pointer dereference away from scribbling all over memory and crashing—or worse, silently corrupting—the application.

A higher-level language should also enable programmers to accomplish common tasks with fewer lines of code and less concern about unimportant details. The code below, which gets an alphabetical list of Apple employees under the age of 50, might be mistaken for a mutant strain of JavaScript or Ruby, but it’s actually Swift.

let ages = [ "Tim": 53, "Angela": 54, "Craig": 44, "Jony": 47, "Chris": 37, "Michael": 34, ] let people = sorted(ages.keys, <).filter { ages[$0]! < 50 }

Even given recent advancements like ARC and collection literals, this code would be substantially longer if written in Objective-C—and the only guarantee of memory safety would be the programmer’s skill. The complete absence of pointers in the code above (and Swift’s bounds checking) provides substantially more safety.

Swift is a convincing high-level language. The basic data types include the expected varieties of numbers, Unicode-aware strings, arrays, and dictionaries, all of which have properties and methods, including literals.

if "hello".hasPrefix("he") { var sillyFour = 5.predecessor() ... }

Any type can be extended, including the standard types like strings and numbers. It only takes a handful of lines of code to make an expression like 99.bottlesOfBeer() print the expected song for any integer value. It’s even possible to extend other classes that can be initialized from strings (e.g., a URL class), enabling code like "http://arstechnica.com".host to parse the string as a URL and return the host name.

High-level-language programmers should be feeling pretty comfortable by now, but it gets better. Despite its rich feature set, the Swift language itself is actually quite minimal. All the basic data types are not part of the language proper. They’re part of the Swift standard library that is loaded automatically by the compiler—and the Swift standard library is written in Swift.

All the string and integer literals and variables in the code samples above are using these basic types defined in the Swift standard library. There’s no artificial distinction between primitive and object types as there is in Java, for example. You don’t have to ask for the “fancy” types that support associated methods and attributes; all Swift types do. From an external perspective, Swift is much closer to the “everything is an object” philosophy embodied by languages like Python and Ruby than it is to Java, let alone a lower-level language like C or C++.

Still not convinced? When Apple says Swift aims to be “as expressive and enjoyable as a scripting language,” it’s not joking. A text file containing the code below will run as expected.