The Swift language, successor to Objective-C
To replace Objective-C, Apple has designed a new language, capitalizing on advances in the field of programming languages, to speed up development and execution time.
The language has been influenced according to the authors by C#, Objective-C, Haskell and many others (see the description of the syntax below). With the use of a retroscope maybe. It is based however on LLVM tools and produces native code. So a very old syntax with a modern backend.
The comparison to Go comes naturally in mind because Swift wants to succeed to Objective-C while Go wanted to do the same to C++.
Actually Swift takes some syntax elements from Go:
- If condition without parentheses with a bracket at right like in Go.
- The same applies to the for loop.
- fallthrough constructs in switch, which is the inverse of the break in C, here coming from Go.
- The word func to define a function.
- The word print displays a message since version 2. In version 1 it was println like in Go.
- Optional semicolon. This is also the case in JavaScript.
- No exception handling.
However, it differs from Go on many key aspects, including the use of inheritance when Go uses composition, concurrency is a library for Swifth, Go lacks genericity. Go further is a minimalist language (only one loop construct) while Swift aims to integrate all possible elements to each aspect of the language.
Swift was initially proprietary but on December 3, 2015, Apple made the code open source (compiler + library). It requires XCode to make a program. It comes immediately with extensive documentation, a complete tutorial and a playground as TypeScript to test the code. In fact its design began in 2010, that left four years to prepare its public distribution.
Language features...
- Compiled with Clang to produce binary code.
- Compatibility with Objective C and C libraries thanks to "bridging header" intermediate interfaces (but not with Objective-C++).
- No macros.
- No coroutines or concurrency in general. This can be provided by an extension like GCD.
- Classes are passed by reference and structures by value.
- Many primitives similar to Julia or JS annotations: Int32, UInt, UInt8, String, Float, Double, Bool, etc ...
Int is equivalent to Int32 or Int64 depending on the OS. - Nil equals empty.
- Memory is managed automatically by reference counting, so no garbage collector.
Syntax description
Displaying Hello World!
print("Hello World!")
Variables may be inserted into a string with the operator \() that unlike $ in PHP allows to mark the end of the variable name.
Type defined by inference
As in Go, Julia, and many scripting languages.
var x = 10
The integer value assigned gives to x the type Int. The type can not change as it would be the case with a dynamic language.
Explicit type
It has become common that variables are defined by var and the type specified as an option, but as far variables are not dynamic as in Julia.
var s = "hello" : string
Constant
Constants are defined by let. We do not see the advantage over const and let has a different meaning in other languages like JavaScript or BASIC which originally brought the word to any assignment.
let x = 10
Tuple
A tuple can be dispatched automatically to provide multiple returns to functions or destructured assigments.
let tuple1 = (1000, "hello")
let (x, y) = tuple1
x get the value 1000 and y the value "hello".
If control structure
Takes the principle of Go: no bracket, but mandatory braces:
if x == 10 {
print("equal to 10")
} else if x < 10 {
print("less than 10")
} else {
print("more than 10")
}
For loop
The loop in a range is similar to that of Ruby and Scriptol. Swift uses ..< for an exclusive range, ... for an inclusive range and Ruby uses ... for an exclusive interval.
Double dots are used in typography to represent an interval, that was also copied by Bash, while ellipsis is the symbol of an indefinite suite.
Python uses the syntax of ALGOL 68.
for var i in 1 ... 10 {
print(i)
}
The format of C was also implemented to enable choice of the increment. A step option like in BASIC could have been added instead.. It is deprecated in Swift 3.
For in applies to a collection, which is now implemented in all languages, even in C++.
for x in somelist {
print("Item \(x)")
}
The classic example to display the letters of a string is as simple in Swift as in Python.
for c in "demo" {
print(c)
}
A tuple is used to obtain the key-value pairs in a dictionary.
let liste = [ "a" : "apple", "b" : "orange", "c" : "berry" ]
for (k , v) in liste {
print("\(k) = \(v))
}
While and repeat while: BASIC language retro mode
For some reason, the do ... while loop in version 1, inherited from C (1972) is replaced by repeat ... while which remiinds of repeat until in BASIC (1964).
while x < y {
}
repeat {
} while x < y
Switch
It solves the issue of common processing to multiple cases by separating them with a comma. Like Go it can also use the reserved word fallthrough to chain clauses. Intervals are possible like in scriptol.
One can also use tuples in the cases but only to compare to an initial tuple.
switch x {
case 1:
print("1")
case 2, 3, 4:
print("between 2 and 4")
case 5 ... 10:
print("between 5 and 10")
default :
print("another value")
}
The break and continues clauses associated with a label in a switch inserted in a while loop makes is possible to jump to an instruction or move to the next iteration.
Pattern matching
The case of the switch statement may contain conditions with the where clause. The principle of pattern matching goes back to the SNOBOL language (1962). Python got pattern matching through an extension named SnoPy.
switch x {
case y where y < 10
case z where x + z = 20
}
Function
The syntax is inverted with respect to C, as it is the fashion with new languages. A function supports multiple returns, default arguments. You can nest functions within another function, that are inaccessible outside of it.
func myfunction(s : String) -> String {
s += "suffix"
return s
}
Multiple returns is achieved with a tuple. The name of the returned variable must be defined in both the header and the return instruction.
func pair(x : Int, y : Int) -> (a : Int, b : Int) {
a = x * 2
b = y + 5
return(a, b)
}
Variadic parameters are demoted with three dots, inspired by C, a sign which is relevant here.
func listing(x : Int ...) -> Int {
var a, b, c
(a, b, c) = x
}
listing(5, 10, 20)
The argument x is actually an array but it does make a difference at the function call.
Classes and inheritance
Classes have single inheritance and multiple interfaces, such as in Java, C#. The constructor is called init rather than "constructor" or rather than the name as the class, maybe because it is more general.
class Vehicle {
var speed : Int
var name : String
init(s) {
speed = s
}
func getname() {
return name
}
}
class Car : Vehicle {
var passengers : Int
}
Protocol
Interfaces are called protocol to be original. They can be typed or generic. Inspired by C# with its getters and setters: the words get and set specify whether you can read or assign a property.
protocol moninterface {
var i: Int { get set }
var name: String { get }
}
An interface (protocol) is inherited like a class:
class car : moninterface {
var name : String = "hello"
}
Extensions
Traits here are called extensions. This allows you to add methods to existing classes. We see here the influence of Rust : changing the name of common elements of languages gives them an air of novelty!
extension tentimes {
var up : Int { return self * 10 }
}
var ten : Int = 10
print(ten.tentimes)
Who will use Swift ?
The adoption of Swift should not be a problem for developers on Apple's mobiles. They already use a language particular to the platform, Objective-C, and migrating to a more modern and compatible language can only improve their experience. But they are not in a hurry.
LLVM bitcode production could potentially provide access to Android, but only if the application does not use Apple's framework and if XCode is no longer needed. The same restriction applies to other operating systems.
The authors also develop the language for a server side use and several frameworks exist for this use. Useful components are implemented in the Open Swift project. But by 2017, Swift is not ready outside mobile use and as each new version adds incompatibilities with the previous one, it is better not to use it before it is completely stable. Especially since its documentation is not up to date either. In addition it is seriously usable only with XCode, so on Apple only.
Site: Swift.