Top 10 Features of Swift Language Syntax for JavaScript Developers
Swift is Apple’s new language for Cocoa and Cocoa Touch, created as an evolution of Objective-C and intended for native OS X and iOS development.
Reading Swift’s new documentation I found a few of its features very interesting. Some of these new features are typical of other high performing languages such as C, Java, etc. Long time ago I used to code in C and C++ and now, years later, I still miss some of the more advanced language syntax in Javascript. Although some go as far as saying that “Swift is basically JavaScript on steroids”, the two have different goals (web vs. native).
#1. Constants
Such a simple thing and such a great help. I’ve always missed constants in JavaScript. A variable is declared with the keyword var
a const with let
.
let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0
Note: All the code samples have been extracted from the docs.
Read the official documentation about Constants
#2. Strong Type
Some people attribute some of the success of JavaScript to loose typing. Although it gives the language an incredible flexibility it also makes it harder to debug and more prone to runtime errors.
In Swift you can indicate the expected value type that a variable is to store as follows
var welcomeMessage: String
Swift is type safe, which means that it will always enforce the right type to be used in expressions. If the wrong type is passed in an assignment or feature call, compilation will fail.
Type declaration is not mandatory and so Swift uses type inference to determine the type of variables if not specified during creation. This is done by examining the values provided in code.
Read the official documentation about Type Safety and Type Inference
#3. Tuples
A tuple is a type that groups multiple values into a single compound value. It is a short way to express complex structures without defining an object.
let http404Error = (404, "Not Found")
// http404Error is of type (Int, String), and equals (404, "Not Found")
Very convenient as the return value of functions. (self link ####)
Read the official documentation about Tuples
#4. Range operator
The range operator is a shorthand way to define a range of values. It comes in two flavors closed and half-closed.
The closed range operator includes all the values in the expression. In the example below values 1, 2, 3, 4 and 5.
for index in 1...5 {
println("(index) times 5 is (index * 5)")
}
The half-closed range omits the last value (very useful when iterating over arrays or lists).
let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..count {
println("Person (i + 1) is called (names[i])")
}
Read the official documentation about the Range Operator
#5 The (supercharged) Switch Operator
Compared with JS, Swift’s switch operator is really powerful control flow operator. I’ve never been a fan of the switch command, but I could grow to like it in Switch.
Since Swift has tuples and ranges, the case
expression of a switch command can be more elaborate and more useful. Swift also includes new concepts to control the flow such as the fallthrough keyword, value bindings and the where
clause.
Range matching case: A case clause can match a range of values, not just a single value.
let count = 3_000_000_000_000
let countedThings = "stars in the Milky Way"
var naturalCount: String
switch count {
case 0:
naturalCount = "no"
case 1...3:
naturalCount = "a few"
case 4...9:
naturalCount = "several"
case 10...99:
naturalCount = "tens of"
case 100...999:
naturalCount = "hundreds of"
case 1000...999_999:
naturalCount = "thousands of"
default:
naturalCount = "millions and millions of"
}
println("There are (naturalCount) (countedThings).")
// prints "There are millions and millions of stars in the Milky Way.”
Tuples matching case: values can be tested against tuples
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
println("(0, 0) is at the origin")
case (_, 0):
println("((somePoint.0), 0) is on the x-axis")
case (0, _):
println("(0, (somePoint.1)) is on the y-axis")
case (-2...2, -2...2):
println("((somePoint.0), (somePoint.1)) is inside the box")
default:
println("((somePoint.0), (somePoint.1)) is outside of the box")
}
// prints "(1, 1) is inside the box”
Read the official documentation about the Switch Operator
#6. (Advanced) Function syntax
The regular syntax of a function is Swift is slightly different from JavaScript in order to accommodate for the parameter and return type definition.
func sayHello(personName: String) -> String {
let greeting = "Hello, " + personName + "!"
return greeting
}
CoffeeScript guys might like the use of the ->
, and might find it more familiar than regular JS folks, specially when dealing with Swift’s closure syntax.
Besides the new syntax, the most powerful new features of functions in Swift are multiple return values, external parameter names & Variadic Parameters.
#6.1. Multiple Return Values
A function in swift can return a complex value as a tuple type.
func count(string: String) -> (vowels: Int, consonants: Int, others: Int) {
var vowels = 0, consonants = 0, others = 0
for character in string {
switch String(character).lowercaseString {
case "a", "e", "i", "o", "u":
++vowels
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
++consonants
default:
++others
}
}
return (vowels, consonants, others)
}
#6.2 External Parameter Names
Functions in Swift can expose the name of each parameter to use when calling the function. This helps readability by indicating the purpose of each argument and reduces errors.
func someFunction(externalParameterName localParameterName: Int) {
// function body goes here, and can use localParameterName
// to refer to the argument value for that parameter
}
#6.3 Variadic Parameters
A feature of crazy name (at least to my Spanish ears), used to indicate that a parameter can accept zero or more values of certain type.
func arithmeticMean(numbers: Double...) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5)
Read the official documentation about Functions
#7 Enumeration type
It’s such as a small thing but, just like constants, it can make your code so much more clean, readable and less error prone.
enum Planet {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
Read the official documentation about Enumerations
#8 Classes and structures (aka Object Oriented Programming)
Native support for classes.
class SomeClass {
// class definition goes here
var width = 0
}
OOP is simple but powerful and with classes come all sort of good things:
- Inheritance
- Getters and setters
- Property Observers
- Native
self
property - Type (aka static) methods
- etc, etc
Read the official documentation about Classes and Structures
#9 Automatic Reference Counting (aka Smart memory management)
One of the great features of Swift that many developers of Objective-C are anticipating. Here’s the description directly from Apple’s documentation:
Swift uses Automatic Reference Counting (ARC) to track and manage your app’s memory usage. In most cases, this means that memory management “just works” in Swift, and you do not need to think about memory management yourself. ARC automatically frees up the memory used by class instances when those instances are no longer needed.
Read the official documentation about Automatic Reference Counting
#10 Generics
Not present in JavaScript but popular in C++. Generics are functions and complex types that don’t require an explicit specific type (Int, String, etc) but instead work with any type indicated at creation.
func swapTwoValues<T>(inout a: T, inout b: T) {
let temporaryA = a
a = b
b = temporaryA
}
Mostly used for collection classes (Array
and Dictionary
types are actually generic collections in Swift).
Read the official documentation about Generics
In closing
Swift lies somewhere between Objective-C and JavaScript. Should be much easier to pick up for those JavaScript developers itching to learn development in the Apple ecosystem.
Maybe it’s time to try some native coding?
For more goodness on Swift & JS you can check out Swift for JavaScript developers.
June 11, 2014 ☼ code