Swift Programming Language is open source!

Apple finally adhered to their promise from WWDC 2015 of open sourcing their new programming language, Swift. In addition to the source code to the compiler, Apple also released the very first implementation in Swift of the “Foundation” library that serves as the standard library for all OS X and iOS application. All the source – code and everything else was released under the Apache 2.0 license which grants the user of the software the freedom to use the software for any purpose, to distribute it, modify it, and distribute modified versions of it, under the same terms of the license without concern for any royalties. The great advantage of the Apache License is that it’s a permissive license, so software derived or which makes us of the software does not necessarily need to be licensed under the same license which leaves ample room for commercial closed-source software to use Swift.

So far Swift’s application was fairly limited to Apple’s own platform since no compiler or runtime library was available for other platforms. As fantastic as these platforms are to develop for, heck even I use a Mac as my main desktop machine, they only make up for a fraction of a much larger universe (my servers all run CentOS Linux). Making Swift publicly available provides access to this interesting language to a much larger developer community.

Why is the Open Sourcing for Swift so interesting?

First of all, if you’re interested in or currently are developing for one or more of Apple’s platform and are using Objective-C, then you will need to learn Swift, as soon as you can. In case you are not developing for one Apple’s platforms, which include OS X, iOS, tvOS, watchOS, and who-knows-what in the future, then currently, the applications of Swift are fairly limited to a few proof-of-concepts implementations on non-Apple platforms like Linux.

Still, why is Swift so interesting to me? It’s an extremely modern language with clever design elements, a very elegant syntax, strong safety features and, thanks to being derived from the LLVM compiler project, is extremely fast. A few of the especially interesting features for developers are: a cool error handling / exception system and Swift’s  adherence to a protocol-oriented architecture.

In Swift, no values are allowed to be null. If you declare a value as
Int, you have to assign an integer value; if you declare a
String value, it can’t ever be nil.

var exampleString : String
exampleString = nil                   // error !

Trying to set a variable to nil will result in a compiler error. Variables in Swift are only allowed to be nil, if they’re optional variables which are declared with a question mark after its type:

var exampleOptionalString : String
exampleOptionalString = nil           // allowed

The question mark indicates that a value may be assigned to the variable and it equals to X or there isn’t a value at all. Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes. Optionals are safer and more expressive than nil pointers in Objective-C and are at the heart of many of Swift’s most powerful features. Because a variable’s “nullability” can be determined at compile time, a large number of null checks can be avoided. Swift helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents you from passing it an Int by mistake. This enables you to catch and fix errors as early as possible in the development process.

Swift also provides an interesting error-handling system which, in my personal opinion, improves the readability of the code. The system is derived from the older NSError system used in Objective-C APIs. It separates the idea of exceptions into two concepts: errors which are the fault of the programmer, and errors that result from user input or the environment. This distinction is important, because it’s not the user’s fault if the developer failed to check the bounds of an array before attempting to access a value, however the user should be notified if the app failed to save a file because the disk is full.

Based on this, Swift distinguishes between exceptions and errors. Exceptions are thrown by the system and always result in your program exiting with an error. Errors are triggered by problems that the user can at least attempt to deal with. Swift’s syntax requires the developer to be especially cautious about functions that can possibly cause issues.

Consider the following Java-snippet:

try {
            String data = getData();
} catch (Exception e) {
            System.out.println("Exception: " + e.getMessage());

It’s not obvious from the code which of the three lines in the try section may possibly result in an exception being thrown. However, the equivalent code in Swift makes it clear which lines can throw an error:

do {
            try openFile()
            let data = getData()
            try writeToFile(data)
} catch let error {
            println("Error: \(error)")

In Swift, any function that can throw an error is required to be wrapped in a do block, or else their calling method must be marked as throws. In a similar fashion, methods in Java must either be wrapped in a try block or have their calling function list the possible exception that they can re-throw in the signature.
The interesting difference here is that each individual line that can throw an error must be prefixed with try. Anyone reading the code can quickly grasp which line or method might fail; in the given example, openFile and writeToFile are the problematic lines which can cause issues.

Lastly, in Swift, along with many other languages, there is this idea of a data type that contains a list of possible methods that a type respectively a class can implement. Java and C# refer to this as an interface, while C++ refers to it as an abstract base class. In Swift, this is called a protocol.

The following example shows a protocol that defines methods for processing some data:

protocol IntegerProcessing {
                 func processNumber(number : Int) -> Int

Any class can then choose to conform to the protocol like this

class MyNumberProcessor : IntegerProcessing {
                  func processNumber(number : Int) -> Int {
                           return number * 2

Even for a novice developer this might look like very benign stuff. However, the real strength and flexibility comes from the fact that the majority of the Swift standard library and the Swift language itself is largely implemented through protocols. Let’s consider the following simple example of comparing two values. In almost all programming languages, it’s possible to compare to integers to each other using the == operator:

2 == 2    // true

In slightly fewer languages this ability to compare values is extended to Strings (including Swift, but for example not in Java):

"foo" == "bar"  // false

The Equatable protocol in Swift requires that any class that conforms to it (“implements”, in Java/C# parlance) implements a version of the == operator which allows two objects of the same type to be compared against each other.

This philosophy of protocols defining the behaviour of objects, rather than their inheritance tree shapes a larger number of aspects in Swift. It’s an interesting approach to development and I’m eager to see this applied elsewhere.

I believe that these features any most definitely many more are responsible for Swift living up to its designers’ goals of being “fast, modern, safe, and interactive”.

Leave a Reply

Your email address will not be published. Required fields are marked *