Hello folks,

I'll start with a polemic phrase: "Swift is the future". I'm saying this phrase too. In this article I'll tell a little about why I take my hat off to Swift now. I'll cover few key points on Swift 2.0, like LLVM optimization, Generics Specialization, Value Syntax and Protocol Oriented Programming.

List of Contents to this Tutorial



It's all up to the compiler

top

Yeah, It's truth that nothing on this old binary world can be faster than C. This statement remains, however... Swift is now running faster on runtime, why?

Not exactly faster than C, but faster than any application that we could create with pure C on our daily works. With tons of pure C code, hyper-optimized routines, we could create an application running so fast as Swift now, but it can become a monster, with a code impossible to manage across a large team of developers, with Seniors and Juniors in the same space.

This is the point when we all think the same:"well, to let every ordinary developer make the same rich code, we could have a compiler or framework good enough to create a hyper-optimized low level code and give an abstract high level that let all developers interact and create the state of art in terms of software performance while keeping the code readable to a large developer team". Well, this is the base idea behind Swift compiler.

It's all about the compiler... really. As we all know, the LLVM compiles the C and Objective-C code into a low-level Assembly that is then assembled to a machine code. LLVM do the same with Swift code, it compiles an assembly code in the last human readable phase of the whole compilation. At this point, the things become really interesting.

All the hard work necessary to create a super optimized code with C is now done by the compiler, without pain. The LLVM can infer so many things based on Swift code that would be insane to recreate the same performance in an ordinary project. But remember, this is a reality in Swift 2.0 with the implementation of all its new great features. Let's see more the new features that give Swift 2.0 such power.



LLVM and Chris Lattner

top

Chris Lattner was a promising compiler engineer since his early days at the college. Apple hired him at 2005 to work at LLVM compiler and at 2011 gave him a great opportunity: creating a new high-level language that could just work greatly with all his genius ideas on LLVM. With other few developers at Apple, Lattner started the Swift language that year.

Lattner arrived at Apple with high moral and a great responsibility. He corresponded really fast, taking LLVM and Clang to a higher level and he created language features like the C Blocks, a super optimized piece of code that can run extremely fast at runtime due to its treats with Stack memory. If you remember from iOS 4, the Blocks is which makes the GCD possible.

Lattner also contributed creating the ARC feature for Objective-C. As you can see, he is the responsible for the last 5 years of the most advanced features in the Apple development. About Swift, it is the biggest dream of Lattner. A curious thing: he started working on Swift at nights, at his home. For one and a half year he worked on Swift in secret, without telling anything at Apple, not even to his closest friends. Only on 2011 Chris revealed his secret to the top executives at Apple. They loved!

Apple designated few other developers to work on the Swift project and after another one and a half year, the Swift project became the greatest focus of Apple. Can you imagine what was that Lattner's dream? "Create a language that would soon change the world of computing", in the words of Wired magazine.

Just as the creators of C (Dennis Ritchie and Kenneth Thompson) changed the world of computing once, Chris Lattner is doing it again, at this time using the compiler's power!

Now the Apple part in this... I'm suspect to say this because I really love Apple, but let's just take a look how the Apple Marketing is great. The Google language GO appeared for the first time in 2009 and 6 years later and it doesn't even appear in the Top 50 at Tiobe Index nor in the communities. Swift is 1-year-old and it's reaching Top 10 at Tiobe (while Objective-C is in free fall from Top 5).
Tiobe Link

Well, of course there is a big difference between Go and Swift, Go also reach higher ranks at Tiobe during its launch, but come on... The Go was made by one of the creators of C and the Google is behind it, a successful combination that doesn't looks to be working that good. I dare to say that Swift is much more likely to change the "world of computing" that any other language today.

And now, Swift is Open Source, just as Mike Ash wished last year. ;)



Generics

top

One of the things I love most in Swift is Generics! How powerful this is for the developers. However for the Runtime the Generics was a time bomb.

In order to run reliable codes, the compiler should add a lot of checks and double checks to work with a Generic instruction. But no more in Swift 2.0. Again, "power to the compiler!" The LLVM can now infer much more things on our codes, not just looking at one file but looking at the whole project. By doing this, the compiler can create specific versions of our Generics, this is called Generic Specialization.


// Consider a Generic function
func maxFunc(x: T, _ y: T) -> T {
    if x < y {
        return y
    }
    return x
}

...

// In another file
var a = 4
var b:Int = 2 + 3
var c = maxFunc(a, b)

Now with Swift 2.0 the compiler can infer that the above code can be replaced by:


// Version generated by Generic Specialization
func maxFunc(x: Int, _ y: Int) -> Int {
    if x < y {
        return y
    }
    return x
}

With this optimized version, the compiler can guarantee a much higher performance during the RunTime.

This is the same concept applied many years ago to the duality of isEqual: and isEqualToString:. Both do the same job, you can use both on a NSString instance, but the second one can run faster, because it's specialized it can avoid uncessary checks.



Value Syntax

top

This one already exists in Swift 1.x, but now it's much better. The Value Syntax is the opposition to the Reference Syntax that is the one used for C pointers and consequently to Objective-C classes. The C struct and C basic data types use the Value Syntax, so nothing new here.

Just to remember, here is an example of both syntax:
(Objective-C code)


// Value Syntax, memory is copied.
CGRect rect = {0.0, 0.0, 100.0, 100.0};
CGRect rectVS = rect;

rect.size.width = 50;
rectVS.origin.x = 10;

NSLog(@"%@", NSStringFromCGRect(rect)); // Prints {{0, 0}, {50, 100}}
NSLog(@"%@", NSStringFromCGRect(rectVS)); // Prints {{10, 0}, {100, 100}}

// Reference syntax, memory is shared.
CGRect *rectRS = &rect;

rect.size.width = 25;
(*rectRS).origin.x = 10;

NSLog(@"%@", NSStringFromCGRect(rect)); // Prints {{10, 0}, {25, 100}}
NSLog(@"%@", NSStringFromCGRect(*rectRS)); // Prints {{10, 0}, {25, 100}}

As you can see, the both have its usage and value. The thing is that on Objective-C you must know about C pointers and C data types in deep in order to correctly work with Value and Reference syntax. The new in Swift 2.0 is again the ability to infer things, so... "power to the compiler!"

The LLVM can infer much more based on your code and project files. It's able to determine if a variable/constant must use the value syntax or the reference syntax. By default Swift is Value Syntax-based, but you can use both styles if you want by changing the architecture of your code (like creating class wrappers) or by forcing a reference (using the inout instruction). For inout, guess what... the syntax for doing it is the same as in C, with "&". Great!


func fooSum(inout varA:Int, varB:Int)
{
    varA += varB
}

var a = 5
let b = 3
fooSum(&a, varB: b)
print(a)



Protocol Oriented

top

This is the last part I want to talk about, but I think this is the most exciting thing on Swift 2.0. Guess what, again it's a compiler thing: "power to the compiler!", but this time, it's so huge, it's a completely change of paradigm and can really change our way to code things.

The Swift 2.0 is now being called as a Protocol Oriented Programming, in counter-part to Object Oriented Programming. Why is that? Introduced in Swift 2.0, the Protocol Extension is what changes everything. With the power of the Where Clauses, this new protocol feature enable us to think about a whole new world without classes and polymorphism.

First off, as a side effect the Protocol Extension eliminates the Mocks on our tests, which I consider an ugly and unnecessary BTW. Mocks sucks, Protocol Extensions are great and can do the same thing. This is enough subject to other article, for now let's focus on how this new feature can change our world.

You already know that Value Types in Swift is great and powerful. Because the compiler can treat Enums, Structs and Classes at the same way at a lower-level, we can create functions, properties and extensions to all these types and get the same performance at runtime.

Just to illustrate how powerful this feature is, consider this: In Swift standard library, Arrays, Sets and Dictionaries are struct types (actually almost all in Swift standard library are Structs with many Extensions). All these 3 types share the same protocol CollectionType, well this protocol is also shared by many others, like String.

Let's say you want to create an extension to the Arrays and Sets. In Swift 1.x or even in Objective-C you could create a category (called extension in Swift) to the Array and another one to the Set, well you could start duplicating code in this scenario. Now, with Protocol Extensions you can create a single extension to the CollectionType and all the classes that implement this protocol gains the new function for free.

But wait, you may not want to give this function to all the CollectionType, because Dictionaries and Strings will have it too. No problems, with the Where Clause (aka Constraints) you can do it in one single line of code, defining that your protocol extension will act only on collections with a single element type.

Notice that Protocol Extension is completely different than creating Protocol Inheritance (or Hierarchy). The Hierarchy is like subclassing a class, which is nothing new and already exist on Obj-C. Swift calls Extension what we were used to call Category, so Swift 2.0 can create concrete and abstract categories to the protocols, which is completely different than Protocol Inheritance.

Take a moment to think how great this new feature is, it can break paradigms and open our world of possibilities. Some may say is isn't too much and they may think about how to achieve a similar behavior, coding once, in other languages. This is not the point here. Discussing a language is free of how much glue code you could use to achieve the same behavior. Discussing a language is how its syntax and paradigms can change our way to think and code.

This protocol feature in Swift 2.0 is enough to drive us outside the box of polymorphism and classes. Remember, classes try to illustrate the real world, but they have many problems, like the single chain and this is not how the real world works. Languages like C++ try to give classes a little bit more power with the Multiple Inheritance, but... OMG... you know that this attempt is probably one of the worst features ever.

In short, OOP was an attempt to recreate the real world structure and of course create new programming paradigms, but this is not how the real world works. Now with POP we have a new way to think, a new way to deal with the reality and transcribe real world things into our small programming world.



Conclusion

top

From this article, would be nice to remember few things:

  • Swift performance comes from the compiler
  • Swift 2.0 is about to change our paradigms
  • Swift is the future

I'll start writing a series about Swift, talking about its new features, its secrets, sharing Playgrounds and algorithms. See you there.

© db-in 2017. All Rights Reserved.