Random ramblings about Mac, Python, TeX, programming, and more  |     |          |     |  

A new language: Swift from Apple

June 3, 2014  |  os-x, programming, python

I've just developed my first application in Swift, the new language announced by Apple yesterday. I downloaded the Swift book on my iPad during the Keynote, and started programming immediately. When I got hold of Xcode beta 6 I got it running in seconds.

My first impression: Swift is a modern language. It is closely related to popular scripting languages, like Python and Ruby, but is is a compiled language. It is also a type safe language, but when the type is obvious, the programmer doesn't have to bother with it (the compiler infer its type). The Swift syntax is easy to read and not strange and new. Important features that often make the syntax of a language complex and unreadable is actually quite clear in Swift (including generics, protocols and extensions). This is a class Amplifier implementing a protocol VolumeControl:

protocol VolumeControl {
    var level: Int { get }
    mutating func increase() -> Int
    mutating func decrease() -> Int
    mutating func mute()

class Amplifier: VolumeControl {

    var level: Int {
        didSet {
            if level < 0 { level = 0 }
    var step: Int
    var source: String

    init(level: Int = 0, step: Int = 1, source: String = "dvd") {
        self.level = level
        self.step = step
        self.source = source

    func increase() -> Int {
        self.level += step
        return self.level

    func decrease() -> Int {
        self.level -= step
        return self.level

    func mute() {
        self.level = 0

    func selectSource(source: String) {
        self.source = source


The protocol specifies one attribute with a getter and three methods. The class implements this protocol by providing access to the attribute and implementations of the methods. The didSet on the property is used to ensure that its value is never negative. The default values in the init method arguments means that these arguments are optional. We can create instances of Amplifier like this:

var a1 = Amplifier()
var a2 = Amplifier(level: 3)
var a3 = Amplifier(level: 1, step: 2)
var a4 = Amplifier(level: 10, step: 5, source: "phono")

But more interestingly, we can access the implementation through a protocol (and only have access to what the protocol provides, not everything from the class instance):

var v: VolumeControl = a1
var level = v.increase()
if level > 100 {
    level = v.level

A good place to start is A Swift Tour. More on Swift later.

Last updated: June 3, 2014