6 things I love about the Swift programming language

The title for this post was supposed to be “6 things I love about Swift”. But then a quick search on Google revealed that most of the world thinks about Taylor Swift and not Swift the programming language. Who knew there was another famous Swift in this world. So just to clarify this post is about Swift the programming language, not Taylor Swift.

It’s been almost a year since WWDC 2014 when Apple introduced Swift. We had the chance to try it and discover what it’s all about. And I think it’s fair to say that a lot of people are very excited about this new programming language and have already started using it. I am amongst those people and today I’d like to share with you my favourite Swift features.

1. Type inference

In Swift, you don’t have to specify the type of every constant and variable that you declare. Swift uses type inference to work out the appropriate type. The compiler will deduce the type of an expression based on the values you provide.

You could declare a constant String like this:

let name: String = "Vasilica"

However, you don’t need to specify the type. You can declare it without specifying the type and the compiler will infer that the type of name is String:

let name = "Vasilica"

Type inference is possible because Swift is a type safe language. This means that it performs type checks when compiling the code and flags any mismatched types as errors. And this enables developers to catch and fix errors early in the development process.

2. Strings

We use strings a lot when developing iOS applications, especially for the UI. Remember this:

NSString *name = @"Vasilica";
NSString *surname = @"Costescu";
    
NSString *fullName = [NSString stringWithFormat:@"%@ %@", name, surname];
NSString *fullName2 = [name stringByAppendingString:surname];

In Objective C the syntax for string manipulation wasn’t that straightforward. Swift’s syntax for string creation and manipulation is lightweight and readable. Notice that you don’t have to prefix all your string literals with the @ symbol. In Swift the code above will look like this:

let name = "Vasilica"
let surname = "Costescu"

let fullName = name + surname

Swift’s strings are mutable, so you don’t have to choose between NSString or NSMutableString. If you want to declare an immutable string just use let, not var. It’s also good to remember that String is a value type. That means that if you assign a string to a variable, a constant or pass it as an argument to a function, its value is copied. This is great because no matter where you got the string from, you know that your copy won’t be modified behind your back.

3. Switch statements

In Swift, the switch statement became much more powerful. Unlike Objective C, where you could only match primitives, in Swift your switch statement can match any type. You can even have range matches, tuples or even complex matching patterns. And your switch cases don’t fall through, so no more errors due to “I forgot the break for my case”.

Let’s see an example of this upgraded switch:

let score = 250

switch score {
case 0...99:
    println("Keep playing, you'll get there")
case 100...499:
    println("Not bad")
case 500...1000:
    println("Nice score!")
default:
    println("You're awesome!!")
}

Here we are using the range matching feature of Swift. Every switch statement must be exhaustive, so if you’re not matching every possible value then you should add a default case. The example above only scratches the surface. You can use switch with tuples, you can even have the case bind the value or values it matches to variables or constants that you can use inside the case. You can also add a where clause to a case to check for additional conditions. Be sure to check the chapter about “Control Flow” from the Swift book and learn more about how to use this updated switch.

4. Tuples

Gone are the days when you had to create a new class or struct just because you wanted to group two values together. Of course, you can still do that and in some cases should do that, but now you have an alternative. With tuples you can group multiple values into a single type. Unlike classes and structs, you can create a tuple without explicitly defining a type. The values within a tuple can be of any type and do not have to be of the same type.

let book = ("The Swift Programming Language", 2014)
println(book.0)
println(book.1)

You can decompose the tuples into separate constants or variables, you can ignore the values that you don’t care about and you can even name the components of a tuple. Tuples are really useful as the return value for functions. Sometimes it just makes sense to return two separate values. Not having to define a new type in order to do that is a very nice touch.

5. Closure expressions

Closures are self-contained blocks of code that you can invoke and pass around. Swift closures are similar to blocks in Objective C.  Closure expressions are the unnamed closures that can capture values from their surrounding context. What I love about these is their lightweight syntax. Let’s see what I mean when I say that.

addPlayerToScoreboard("Vasi", { (score: Int, level:Int) -> Int in
    return score * level
})

However, as I was saying earlier Swift knows how to infer the type of the parameters so there’s no need to explicitly write it. Because all the types can be inferred we can omit the return arrow and the parentheses around the names:

addPlayerToScoreboard("Vasi", { score, level in
    return score * level
})

Because we only have a single line of code in our expression we can omit the return keyword. The result will be implicitly returned:

addPlayerToScoreboard("Vasi", { score, level in score * level})

This already looks pretty simple without all the boilerplate code around it. We can take it a step farther and use shorthand argument names. Swift automatically provides shorthand argument names to inline closures, which can be used to refer to the closure’s arguments by the names $0, $1 and so on. If you use these shorthand argument names within your closure expression you can omit the closure’s argument list from its definition. We could write our code like this:

addPlayerToScoreboard("Vasi", { $0 * $1 })

This might be taking it a bit too far for our example. Our code became less readable and you wouldn’t be able to tell straight away that we’re calculating the total score based on the intermediate score and the level. While you can make the syntax very lightweight, you should still use common sense in deciding just how much you’re going to reduce the code.

I can see this feature being misused, but I still love how powerful and simple the end result can be.

6. Generics

I remember generics from my days as a Java developer. I loved generic collections and the way you could make your code more reusable with generic types. In Objective C, you could put objects of different types in a NSArray. In Swift, both Array and Dictionary are generic collections. You cannot create an array that contains both String and Int types. This might seem like a bad thing, but it takes out the guessing from your code. The only way to know what kind of objects an Objective C array contains is by the name of the array or by looking at the documentation. However, even if your documentation says you will receive one type of objects, the compiler is not preventing you from adding a different type. With Swift, if you specify that your array will contain Strings and you try to add an Int you will receive a compile time error.

Arrays and dictionaries are not the only place where you can use generics. You can use generics to avoid code duplication. Suppose you have a function to swap two integers. Because Swift is a type safe language you can’t use the same function to swap two floats or two strings or even two objects of a type you have defined. You would have to write code for each case. This is where generics come to the rescue. You can write the code like this:

func swapTwoValues<T>(inout a: T, inout b: T) {
    let temporaryA = a
    a = b
    b = temporaryA
}

Instead of specifying the type of the parameters you specify a placeholder type name. You can use this function with parameters of any type, just notice that both parameters have to have the same type.

This is just a taste of how powerful generics can be and how it can help you write flexible and reusable code.

Conclusion

I like Swift and I can see how Apple cherry picked the best features from the existing languages and combined it all to create this brand new language. I love how it is so focused to protect the developer from common errors, how light and simple the syntax is and how flexible Swift is. These are just a few of my favourite Swift features. The list keeps growing as I keep learning and using Swift for my projects. What are your favourite Swift features?

One thought on “6 things I love about the Swift programming language

  1. Returning to coding after an absence to run and grow a startup, I am delighted with Swift. I had begun my reintroduction with ObC and found the syntax convoluted. Swift is a breath of fresh air. I’ve been powering through the learning and was deploying useful prototype apps in just 5 weeks from a cold start. Another thing I like about Swift is the IDE. The build out of the UX is vastly simplified. Thanks for the great post. I’ll be passing this one around.

Leave a Reply

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

*