What is Swift?
Swift is Apple’s new programming language, which has been in development for the past four years and which looks to replace Objective-C as the main language for app development on Apple’s platforms, OSX and iOS.
It’s a major departure from the syntax of Objective-C and takes a lot of cues from other languages, such as Haskell, C#, Ruby and Python, which Apple presumably hopes will make it appealing to bright young coders, keen on modern languages.
Although it’s a major departure, Apple have taken a lot of trouble to make the transition to Swift as painless as possible. It is fully binary compatible with existing Objective-C libraries and maintains a close relationship with the Cocoa frameworks.
That means that developers can introduce Swift into their apps at their own pace, by writing discrete modules that should seamlessly interoperate with their existing Objective-C code.
What are the improvements around Objective-C?
In Swift there is no need to annotate variables with type information as the compiler can infer type based on the value a variable is being set to. Due to the dynamic nature of Objective-C, type is not truly known at compile time because methods may be added to existing classes, entirely new classes added or instance type changed all at runtime.
With Swift, the compiler can be more helpful in catching subtle type related bugs. As the compiler knows more about type in any method call, it can optimise certain call sites and jump directly to the implementation using C++ style vtable dispatch, rather than going through dynamic dispatch as in Objective-C. This enables smart optimisations that can make code run faster.
The humble switch statement has undergone a radical overhaul in Swift and can now match against ranges, list of elements, boolean expression, enums amongst others. It doesn’t fall through by default, and is further enhanced by Swift’s flexible pattern matching.
An optional type is a type that might contain a value of a type. It allows you to more easily convert between types and avoid null checks. Optionals can be chained together to protect from exceptions when calling multiple methods or properties in a chain where one call might return “nil”.
Strings are now easier to deal with in Swift, with a cleaner syntax than Objective-C, eg: concatenate strings using “+=“.