Journal OSX

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”.


Korean Artist Beautifully Illustrates What True Love Is All About



This post is completely off-topic and not at all technical related but I still wanted to write about it since I just love the illustrations shown later.

So, I am sure you have all seen enough grand gestures in Hollywood movies and Korean Dramas in order to declare the protagonists’ love to the man or woman of her dreams. Nevertheless, I often hear the question and even ask myself: What is true love?

Korean illustrator Puuung (퍼엉) believes that true love lies in the little things. It is about the simple yet intimate moments in our everyday lives and making them last a life time.

Puuung writes on her Facebook page: “Love is something that everyone can relate to. And love comes in ways that we can easily overlook in our daily lives. So, I try to find the meaning of love in our daily lives and make it into artworks.”

Puuung’s beautiful illustrations capture the depth and extend of a couple’s love by showing them share memories of joy, peace, small surprises and sorrow.

Some of my favourite illustrations:
34A7o3g 9JvK9eg ouzku7U f4s981p 3eeUSOo N5aNOgB gYYXzCu njDHYel RE7AQkc trznQRe rfk9gRC UOCweL2 opyFgYv Qf71ZqK 5v1vAoA YXOoaTt tu0OYS5 Doob3JS onr56uy tmZ663H

Journal Linux

Laptop Power Saving with powertop on Fedora 22

The most important thing you want from a laptop is long battery life. Ever ounce of power you can get to work, read or simply just entertain on a long jaunt. Therefore, it’s always good to know what is consuming your power.

Intel’s powertop utility shows what’s drawing power when your system’s not plugged in. Use dnf to install powertop:

sudo dnf install powertop

powertop requires direct access to the hardware to measure power usage so you have to run it with root privileges:

sudo powertop

The powertop ouput will look similiar to the screenshot below. The measured power usage as well as system wakeups per second will most likely be different:

Screenshot of Powertop
Powertop 2.7 on Fedora 22

To switch between the multiple tabs use either the Tab or Shift+Tab keys. To quit the application, simply hit the Esc key.

The utility not only shows the power usage for various hardware and drivers but also displays the CPU stepping modes as well as systems wakeups per second. Processors are often so fast that they idle for the majority of the time.

The best way to maximize battery power is to minimize the number of wakeups per second. The best way to achieve that is to use powertops’ Tunable tab to optimise your laptop’s power savings. “Bad” usually indicates a setting that’s not saving power. In contrast, it might actually enhance the performance. “Good” indicates a setting is tuned to save power. Use the Enter key to turn any tunable on/off.

If you like to automatically turn all tunables on, the powertop package also includes a service that automatically sets all tunables to “Good” for optimal power saving. To start the service enter the following command:

sudo systemctl start powertop.service

To automatically start the service on boot time  enter the following command

sudo systemctl enable powertop.service

Probably the only caveat about this service and the tunables in general: Certain tunables may risk your data or result in some odd hardware behavior. For example, the “VM writeback timeout” settings affects how long the system waits before writing any changes of data to the actual disk. So you actually trade off data security for power savings. If the system loses all power for some reason, you might lose all the changes you made in the last 15 seconds, rather than the default 5. Nevertheless, for most laptop users this isn’t an issue since the system should warn you about low running battery.


Source Code Formatter for Blogspot

Add the following CSS Style to your Blogger template

pre.source-code {
font-family : Andale Mono, Lucida Console, Monaco, fixed, monospace;
color : #000;
background-color : #eee;
font-size : 12px;
border : 1px dashed #999999;
line-height : 14px;
padding : 5px;
overflow : auto;
width : auto;
text-indent : 0px;

surround your code with the following tags to add the source-code formatter: