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).

Apple Swift Logo

#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.

Underscores in Apple’s Swift Numbers

I’m catching up with Apple’s new language Swift, and this declaration of numbers caught my attention: in order to help readability numerals can be written with underscores (eg: 12_345).

Apple Swift Logo

Numeric literals can contain extra formatting to make them easier to read. Both integers and floats can be padded with extra zeroes and can contain underscores to help with readability. Neither type of formatting affects the underlying value of the literal:

let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1

Excerpt From: “The Swift Programming Language.”.

I also just learned that this feature is already present in some languages such as Perl, Ruby and Java but not in Javascript 🙁

I like the idea of not only creating new languages, but rethinking how we write code and how we can improve the coder experience (after UX, we now need a new field of CX).

On The Changing Advertising Ecosystem

This article does a fair job at covering some of the changes the industry is going through in recent years.

Burned by the recession, clients are loath to greenlight risky work and bottom-line pressures are driving them to wring costs from their shops. To grow, independents are selling to public holding companies and succumbing to the balance-sheet demands that can dull a free-spirited culture. Often, the result is chasing business they might once have scorned while private.

[…] Fees have gotten smaller and once-huge accounts have become projects doled out to multiple agencies. “Now accounts are half the size they used to be. [Agencies have to] pitch more, because there’s more project work, fewer AOR opportunities and even those are half as much as they used to be.”

~A Tale of Two Crispins: Why There Won’t Be Another Agency of the Decade

We Need Less “Content Marketing” And More “Meaningful Marketing”

TL;DR: “Content marketing” should focus less on content creation and more on meaningful connections made possible by valuable content

We —those in the business of marketing on the web— have a constant obsession with newness, with defining today’s zeitgeist, with being current and relevant, etc. One of the new terms that’s being abused these days is “Content Marketing”. A concept that seems old if looked closely. Brands need to do much more than just blast their messages left and right, they need to create content to engage their customers. But since when is this new? Brands always had that duty, and good ones delivered on it by creating their own content (commercials, radio plugs, print ads, etc) or by supporting 3rd party content.

Branded entertainment is a significant departure from previous brand marketing strategy […] The rise of branded entertainment is enabling brands to shift from being mere sponsors to creators. We’re all used to seeing brands sponsoring entertainment as a means to get their logo and messaging in front of consumer eyeballs […], now brands are becoming destination sites and platforms for entertainment, in and of themselves.

Let me entertain you: The rise of branded entertainment

Yes, brands need to entertain but that’s nothing new. The term “Content Marketing” places all the focus on content. Brands have always created content. What some have neglected is creating a lasting connection with the consumer. When these were created they were in an offline mode, meaning the messages where sent out and the customer could never participate. Because connections had that offline, non-realtime quality they were emotional connections, the ones with the highest chances to stick. We should bring that back.

The web has made one-to-one connections possible. Because of this the true focus of “content marketing” should be the creation of content that the consumers can (and want to) engage with, thus creating those connections. The Brand’s challenge is creating content that can rise above competition and that can be valuable enough to create a lasting relationship with its audience.

If I could I would rename “Content Marketing” to “Meaningful Marketing”.