my digital playground

Top 5 Swift Features Briefly Explained: Closures, Generics, Type Inference, Multiple Return Types and Namespaces

When announcing Swift at the WWDC 2014 on Monday (see Swift announced), five features of the new language have been highlighted during the presentation:

  • Closures
  • Generics
  • Type inference
  • Multiple return types
  • Namespaces

Closures are functions that have access to all data that are in scope of where the closure has been created (e.g. local variables of the function that created the closure). If that data is out of scope for any other function – e.g. the creator of the closure is a function that already has returned – then the data is still alive because the closure set a reference to this data. Thus, the garbage collection won’t trash this data, even if it was a local variable inside a function that has returned. Of course, assuming there is any reference to the closure itself.

  • Closures are comparable to local classes in Java.
  • Closures are similar to blocks in Objective-C.

Generics allow program code to be independent from the data types by its variables. For example, a function that uses parameters as input data doesn’t have to know for what kind of data type it is written for. Basically, the function is simply generic for any type of data.

  • Generics are similar to Templates in C++.
  • Objective-C is a dynamically typed language. That means the compiler does’t always check for correct types. It’s the programmer’s duty. Generics make sense in strongly typed languages like Swift where the Compiler will warn about wrong types. Thus, it’s less error-prone during runtime.

Type inference
Type inference allows to omit the type of variables. Based on the expression, Swift concludes the type automatically. However, the programmer can explicitly specify the type.

  • Type inference seems identical as in Python.
  • Objective-C does not support type inference.

Multiple return types
A function’s return type can be a tuple with multiple values and types.

  • Usage of arrays, structs, lists, etc. can be used to achieve multiple return types in almost every language. Swift’s approach with tuples is comparable to returning tuples in Python.
  • Objective-C does not support tuples but structs or special container classes can be used for this purpose.

A Namespace allows to group together a bunch of identifiers which all belong to the same library, package or functionality in general. Thus, namespaces avoid naming collisions. Otherwise, modern software projects that include libraries from different developers and vendors would have a hard job to assure that no class name occurs twice within the project. Interestingly, I did not find the namespace feature in Swift. Even the documentation does not contain the word “namespace”.

  • C++ use namespaces; Java calls them packages; Python organizes namespaces by modules.
  • Objective-C does not support namespaces. That is why the classes have prefixes in their filenames like NSString or UIButton. This is typical kind of workaround when namespaces are no available.

Swift Announced

At Apple’s WWDC on Monday, 2nd June, 2014, Craig Federighi announced a new programming language called Swift. The main focus shall be:

  • Fast
  • Modern
  • Safe
  • Interactive

Especially the last point was emphasized as “a level of interactivity in development that you’ve never seen on a platform“. Federighi announced Swift as faster:

Complex object:

  • Swift: 3.9x
  • Objective-C: 2.8x
  • Python: 1x

RC4 encryption:

  • Swift: 220x
  • Objective-C: 127x
  • Python: 1x

But actually, Federighi did not compare Swift against Objective-C. Instead, he compared Swift and Objective-C with reference to Python. Thus, giving extrem high values. One could say, he compares apples to oranges since Python is run by an interpreter while Swift is compiled to native code. Also, Swift and Objective-C are used in totally different domains than Python. I don’t think that anyone will ever use Swift where Python has been used before. Otherwise, drop me a line and I will update this article.

The benchmark for Swift with reference to Objective-C would be this:

  • Complex object sort: 139% the speed of Objective-C
  • RC4 encryption: 173% the speed of Objective-C

However, at the end it’s all processor instructions and we don’t know how the performed benchmarks were implemented and optimized. Since Federighi just said faster without explicitly mentioning runtime, maybe the speed comparison was meant about the typing of source code. In that unlikely event, I really wonder who wrote the Python code.

The really interesting fact seems that Swift combines two great things: 1. The speed of native code, like Objective-C. 2. The functionality and ease of a modern high-level language like Python.

So, what’s the catch? Anyone?

oneLineSystemMon: Simple Geeklet That Shows Cpu, Memory, Disk and Transferred Network Data

When working with Linux you may be used to have a system monitor on your desktop like Conky or its ancestor Torsmo. If you are on OS X then you might like to use GeekTool for this purpose.

I put together a script for GeekTool that fits my needs. It will show up as a single line of text on your desktop and shows the load of your CPU, memory, disk and the transferred data on your network interfaces. The output is:

CPU 4.87% – MEM 5179M – SSD 70% – LAN IN:0 Bytes OUT:0 Bytes – WIFI IN:101.531 MiB OUT:13.687 MiB

If you wonder about the green and red color… this is just for my personal convenience to be able to quickly distinguish incoming and outgoing data.

You need a small python script called to show the transferred bytes of the network interfaces in human readable format – e.g. “1.804 GiB” instead of “1936614762”. You can get it from here Please put in in ~/bin to make the geeklet work or edit the geeklet manually.

Download the Geeklet: Geeklets are associated with GeekTool which should start automatically when opening a Geeklet.

GeekTool can handle much more nice stuff than printing one line from a shell script. Google for “Geeklets” and have fun.

Update: I added a second Geeklet to my desktop directly below the above on. It shows the netstat output but only with certain socket states including ‘listening’. It’s too simple to provide a Geeklet file for this one. You just have to add a new Shell GeekLet with the following command in a single line:

netstat -a | grep -e ESTAB -e LIST -e CLOS -e SYN_ -e LAST_ -e _ACK -e FIN_ -e TIME_

This is how my two Geeklets will appear:



Raspberry Pi: Setting Up a Wifi Connection Without Keyboard, Mouse and Monitor Connected

Unlike Ethernet, which is configured to automatically use DHCP on the RPi (Raspberry Pi) by default, setting up a Wifi connection can be difficult to some users. First of all, the RPi can not and should not guess the name of your Wifi network and it surely can’t do so with your Wifi passphrase. I hope you really do not want this.

Now, setting up Wifi can be simple by using the graphical interface and the provided application on the desktop named “Wifi Config”. But this ‘simple’ requires you to have a HDMI display and a USB keyboard/mouse ready to be connected. If not, then you can attach your RPi to your router via an Ethernet cable, then connect via ssh to the command line and then configure your Wifi remotely. Below, this procedure is described in more detail.

Step 1 - Requirements

  • Raspberry Pi with Raspbian “wheezy”
  • Ethernet cable
  • Router
  • A computer which is already connected to your router
  • SSH client software (for Windows systems you can use PuTTY, MacOS and GNU/Linux systems are usually equipped with such a client software)

Step 2 - Set Up

Connect your RPi to the router using the Ethernet cable and power on the RPi.

Step 3 - Get the IP address of your RPi

Boot it up and figure out the IP address of your RPi. Since we don’t have anything but power and ethernet connected to the RPi we can do so by checking the administration utilities of our router or by doing a ping sweep. Another possibility explained by Remi Bergsma is to scan for the specific range of ethernet addresses used by the RPi boards.

Step 4 - Connect via SSH

Use the SSH Client software to connect to your RPi. On MacOS X and GNU/Linux systems you can do so by opening the Terminal application and entering the command ssh pi@ In this case the IP address is and the username/password are the default ones (username: pi password: raspberry). The password will be requested by the SSH client while the connection is established. macy:~ jens$ ssh pi@ pi@’s password:

Step 5 - Wifi Settings

Now you should have access to the command line of your RPi. Type sudo nano /etc/network/interfaces to edit the network interface configuration file. You should see something similar like this:

auto lo

iface lo inet loopback
iface eth0 inet dhcp

allow-hotplug wlan0
auto wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf

iface default inet dhcp

We need to put the information about our Wifi network name and it’s WPA passphrase into this configuration file. Edit your file analogue to this example:

/etc/network/interfaces mark:8-10
auto lo

iface lo inet loopback
iface eth0 inet dhcp

allow-hotplug wlan0
auto wlan0
iface wlan0 inet dhcp
 wpa-ssid "MyHomeNetwork"
 wpa-psk "YourWpaPassphraseGoesHere"
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf

iface default inet dhcp

Save the file and close it.

Step 6 - Verify

Verify your changes by rebooting the system with

sudo shutdown -r now

On success, the RPi should automatically connect to your Wifi network on startup. Please note that your router’s DHCP server won’t assign the same IP address to the Wifi connection of the RPi as it did before with the ethernet connection. Therefore, repeat Step 3.

If you figured out the new IP address you should be able to talk to your RPi as usual (SSH, ping, and so on).

If you have any questions or improvements please feel free to do so. You can use the “Post a comment” feature below. I’ll try to answer and update this article where necessary.

Comment from Anonymous: cwpa_supplicant: wpa-roam can only be used with the “manual” inet METHOD

Jingle Bells Playing Light-up Piano Keyboard

Christmas time is just around the corner and so is the next tinkering project:

it has to do something with Christmas…
it has to do something with software…
it has to do something with electronics…

…Ermm, so the first idea was to put a bunch of colourful LEDs around a Christmas tree. Indeed, that is innovative as putting coloured paper around a gift. So I came up with the idea to make a jingle bells playing light-up piano keyboard by utilizing …well, a tree and LEDs but additionally there‘ll be a speaker ;o)

So, here‘s a little sketch about the idea.


The first challenge is the keyboard design. We need to know how to play jingle bells on a keyboard. As you might know or see on YouTube tutorials, there are several ways to play this song. The easiest way is to use a single note at a time by just playing the melody of verse and chorus. The lowest key I used for playing is a D and the highest key is the E on the next octave. Between those two keys we also need E, Fis, G, A, B, C, D (on the next octave). But keep in mind, you could also transpose the melody to higher or lower notes. So, after figuring out which keys we need I started drawing a keyboard in Gimp. To make things easier, I wrote the name of the note on each key and marked the notes that have to be player with a red dot. Some more keys than necessary a there for a clean look.


Now that we have finished the outer design of the keyboard we need the interior. There was a small non-etched copper circuit board in the tinkering box since years. So this is a good starting point. We can carve a circuit (respectively the boundaries of the tracks) into the copper board by using a box cutter. Then, soldering small SMD LEDs and resistors across the tracks (right over the cut of the box cutter) to connect them to the appropriate nets. This doesn’t only sound like a mess but it also looks like a mess.


Now let‘s put the keyboard design and some descriptions on this messy photo to see what has been done here. Since very small SMD parts were used its quite hard to see. Yes, it‘s even harder to solder. Be a little smarter than me and use bigger parts :–)


Here is an approbate schematic design.


The next thing to prepare is a speaker. If you are lucky you find one in an old walkie talkie device, phone, toy, etc. My speaker looks like this.


I decided to use a NPN-transistor to connect and disconnect the speaker to the voltage source. The idea is to do this with a frequency that equals the musical notes of the song. This will result in a square wave sound which is the very loud and sharp. R1 is used to make the sound more quiet. Push a jumper at position X1 to get out the maximum volume but be sure your speaker can handle the power :–)


Now it‘s time to put things together. We have 9 control lines for the LEDs and 1 line for the speaker signal. We want the device to start playing if a push button is pressed and when done playing the device shall be switch off automatically. For this, we use a pushbutton in parallel to a relay switch which is controller by the ATmega. If someone presses the push button then the ATmega starts running and holds the relay closed. This way the user who pushes the button only has to hold for a few milliseconds until the system runs. If the song has been played then the ATmega shall release the relay signal so that the relay opens and the battery gets disconnected.


The electronic part is ready, now it‘s time for the software to put life inside. The song is an array of 16-bit values (uint16_t song[]) and each value represents the wave period of the appropriate piano key sound. Now, the software just has to iterate through the array, light up the appropriate LED and change the PWM settings according to the current value as read from the array. Additionally, there is a delay function for the timing to switch off the PWM between the notes to make it sound like as if the piano keys are pushed down and released in a very simple rhythm. Here is the source code.

 #define F_CPU    1000000UL

 #include <avr/io.h>
 #include <util/delay.h>

 #define C    3817
 #define CIS  3610
 #define D    3401
 #define DIS  3215
 #define E    3030
 #define F    2865
 #define FIS  2703
 #define G    2550
 #define GIS  2410
 #define A    2273
 #define AIS  2146
 #define H    2024
 #define C2   1906
 #define D2   1701
 #define E2   1515

 // jingle bells me it is!  
 uint16_t song[] = {
   D,  H,  A,  G, D,   0,  0,  D,  H,  A,  G,  E,  0, 0,
   E,  C2, H,  A, FIS, 0,  0,  D2, D2, C2, A,  H,  0, 0,
   D,  H,  A,  G, D,   0,  0,  D,  H,  A,  G,  E,  0, 0,
   E,  C2, H,  A, D2,  D2, D2, D2, E2, D2, C2, A,  G, 0, D2, 0,
   H,  H,  H,  0, H,   H,  H,  0,  H,  D2, G,  A,  H, 0,
   C2, C2, C2, 0, C2,  H,  H,  0,  H,  A,  A,  H,  A, 0, D2, 0,
   H,  H,  H,  0, H,   H,  H,  0,  H,  D2, G,  A,  H, 0,
   C2, C2, C2, 0, C2,  H,  H,  0,  H,  D2, D2, C2, A, G,

 void play(uint16_t sound)
   // sound output  
   ICR1 = sound & 0xFFFE; // set period  
   OCR1A = (sound & 0xFFFE) >> 2; // set pulse width  

   // led output  
     case D:   PORTD = 0x01;  break;
     case E:   PORTD = 0x02;  break;
     case FIS: PORTD = 0x04;  break;
     case G:   PORTD = 0x08;  break;
     case A:   PORTD = 0x10;  break;
     case H:   PORTD = 0x20;  break;
     case C2:  PORTD = 0x40;  break;
     case D2:  PORTD = 0x80;  break;
     case E2:  PORTB = 0x01;  break;
       PORTD = 0;
       PORTB = 0;

 int main (void)
   uint8_t i;
   DDRB = 0x03;  // speaker and relais are outputs  
   DDRD = 0xFF;  // LED 1 to 8 are outputs  
   DDRC = (1<<PC5); // LED 9 is an output  
   PORTC = (0<<PC5); // keep the relais of life tight!  
   TCCR1A = (1<<COM1A1) | (1<<COM1A0) | (1<<WGM11); // pwm settings
   TCCR1B = (1<<WGM13) | (1<<WGM12) | (1<<CS10);  // pwm settings

   for(i=0; i<(sizeof(song)/sizeof(uint16_t)); i++)
     play(song[i]); // play note, switch LED on  
     play(0);    // mute sound, switch LED off  

   PORTC = (1<<PC5);  // release the relais of life...

   return 0;

A small fake fir tree that can be found in a typical decoration store besides tons of other useless stuff makes a great stand for the keyboard and gives a real Christmas touch to it.


Now, here is my realization of the plans above. The front side shows the keyboard and a push button. The push button is at the bottom in between the red ribbon.


The back side shows the 9 volts battery, the speaker and the perfboard which holds the ATmega, the 7805 voltage regulator, the capacitor, the transistor and two resistors.


You may wonder where the relay is gone. I only had a 250V relay in my tinkering box which is kinda big. So I fixed it with a cable tie to the tree. Indeed, this is like using a sledgehammer to crack a nut but the part was already there :–) If you have a better idea (like a solid state relay?) which works fine for this application then please let me know!


Here is a video of the tree in action. Unfortunately, in the video it is quite hard to see that the LED illuminates one key instead of all keys nearby. This looks better in reality.


Just out of curiosity, I tried to create a VGA signal with the Xilinx Spartan-3E Starter Kit. It all ended up as a Pong game with some funny behavior. Feel free to download the project files (created with Xilinx ISE WebPack 12.1) or just watch the video. The project runs at 640x480@60Hz. I learned about the VGA signal timing from here and of course by playing around a lot ;o)

Comment from Anonymous: can you please explain why you thoroughly how you ball is moving?and why you took the cnt value=5000??

Answer: I suppose you mean 50000, right? Well, that’s the speed of the animation as I preferred it. As you can read in the comment above “animation rate = 25 MHz / 50000 = 500 pixels per second”. So, 50000 is the amount of cycles I have to wait to get a result of 500 pixels per second. The less I wait, the faster the animation goes. So, increasing this value slows down the animation speed. Play with the value ;)