Swift for JavaScript Developers

Video & transcription below provided by Realm. Realm Swift is a replacement for SQLite & Core Data written for Swift!

This Tuesday JP Simard gave another talk for the Swift Language User Group (#SLUG) in San Francisco. Hosted by Pubnub, this meetup was a Swift talk for JavaScript developers. JP began with a brief overview of some similarities and differences between Swift and JavaScript. He then focused on eight main concepts in the two languages, including classes, callbacks, and type safety & inference. Thanks to our sponsors - PubNub & DeNA!

Swift Intro (2:32)

At WWDC, the brand new language Swift surprised many developers with its syntactic similarities to Javascript. However, differences begin to emerge once you look past the syntax. For example, the following piece of code runs in both Swift & Javascript. However, the two languages return different things.

var strings = ["a", "b"] // => [a, b]
strings.reverse() // => [b, a]
strings[0] // => Swift: a, JS: b

Similarities… (5:41)

Syntactically, the two languages are very similar. As seen above, the same code can compile and run in both languages. As for tooling, Swift has a new feature called REPL, which stands for Read-Eval-Print-Loop (Ed.). Users can see the effects of code they write in real-time, which allows Swift to still have a scripting feel.

… & Differences (6:33)

Swift is still a compiled language, so it compiles every single time. There are also differences in APIs, libraries, and frameworks, since those are tailored to specific platforms and applications. Type safety & generics make Swift a much safer language in that it prevents the user from passing in incorrect types. Swift also has functional concepts built into the language and the library. A final difference is that Swift will never work backend or in-browser, as there are many issues that will prevent it from being truly useable in a backend setting.

Obstacles to running Swift outside iOS/OSX (9:48)

Three main steps would need to happen to be able to use Swift outside of iOS/OSX. The Swift compiler, runtime, and standard library would all need to be open sourced. To use Swift across platforms, Apple would have to open source the Swift runtime. The first two have happened for Objective-C, but the fact is that the Objective-C standard library is thirty years old and still not open source. Developers may have to wait a long time if the Swift standard library becomes open source at all, in order to use Swift across multiple platforms.

REPL (12:17)

Node.js REPL has been very useful for developers, as in troubleshooting algorithms or other ideas. Now the Swift REPL and XCode 6 Playgrounds allow iOS and Mac developers to see results in real-time without going through the time-consuming compilation step as frequently as before.

Demo (14:15)

The demo was done in an XCode 6 Playground and gave a brief view of Swift syntax. Create a class with the “class” keyword and add propreties. Swift is not so verbose - type inference helps with this!

Eight Concepts in Swift and Javascript (21:35)

1. Classes (22:06)

In JavaScript, there isn’t a fully defined “class”. Instead, a “class” function can have properties.

function Car(model){
  this.model = model;

Car.prototype.drive = function() {
  return 'Driving my ' + this.model;

var car = new car('Batmobile');
car.drive(); // => Driving my Batmobile

Swift classes can add properties and methods.

class Car {
    var model = ""
    func drive() -> String {
        return "Driving my " + model

let car = Car()
car.model = "Batmobile"

2. Callbacks (23:21)

Here, there are syntactically similar concepts between Swift & JS. This code is defining a log function that will log a string.

var log = function(txt, done) {
  setTimeout(function() {
    console.log('callbacks are ' + txt);
  }, 1000)

log('awesome', function() {
  console.log('and done');

The Swift code is more verbose because of what’s available within the Cocoa framework & Swift standard library. Differences between Swift and JavaScript really seem to boil down to differences in their APIs.

func log(txt: String, completion: () -> ()) {
    var delta = 1 * Int64(NSEC_PER_SEC)
    var time = dispatch_time(DISPATCH_TIME_NOW, delta)
    dispatch_after(time, dispatch_get_main_queue()) {
        println("closures are " + txt)

log("not the same as JS closures") {
    println("and done")

3. Promises (25:10)

Promises wrap callbacks in a much more reusable way.

var log = function(txt) {
  return new Promise((resolve) => {
    setTimeout(function() {
      console.log('promises are ' + txt);
    }, 1000)

log('the future').then(() => {
  console.log('and done');

Here again, Swift is more verbose, but still resembles JavaScipt callbacks or Objective-C blocks.

func log(txt: String, #resolve: () -> (), #reject: () -> ()) {
    var delta = 1 * Int64(NSEC_PER_SEC)
    var time = dispatch_time(DISPATCH_TIME_NOW, delta)
    dispatch_after(time, dispatch_get_main_queue()) {
        println("closures are " + txt)

log("not the same as JS closures",
    resolve: {
        println("and done")
    reject: {
        // handle errors

4. Type Safety & Inference (26:38)

Type safety and inference minimize the amount of mistakes in Swift code. The Swift compiler prevents code from compiling when assigning values to variables.

let anInt = 3
let aFloat = 0.1416
var pi = anInt + aFloat // Compile warning

pi = 3 + 0.1416
// Compiles: number literals are untyped

5. Tuples (30:42)

As in JavaScript, tuples allow users to track multiple variables that have more meaning when grouped together. Swift tuples are also strongly-typed.

let http404Error = (404, "Not Found")
http404Error.0 // => 404
http404Error.1 // => Not Found

6. Mutability (31:39)

Swift starts to diverge here from JS. Apple is still changing mutability in Swift - because they are still in development, features are not finalized yet. Swift defines the keyword “var” as mutable and “let” as immutable.

var letter = "a"
letter = b // works

let a = "a"
a = "b" // compilation error

The two languages have different mutability semantics. In JavaScript, both keywords “var” and “let” are mutable, with “let” limiting scope, while the keyword “const” provides immutability (in only FireFox and Chrome). Another way JavaScript deals with immutability is through the freeze() method.

var obj = {
  foo: "bar"

obj.foo = "baz"; // works
Object.freeze(obj); // freezes obj
obj.foo = "bar"; // silently does nothing

7. Functional Programming (37:03)

JS does functional programming well in third party libraries, but not in the language itself. On the other hand, Swift has built-in functional programming, like the map and filter functions.

let numbers = [1, 5, 3, 12, 2]
numbers.map {
    (number: Int) -> Int in
    return 3 * number
} // => [3, 15, 9, 36, 6]
numbers.filter {$0 % 2 == 0} // => 12, 2]

8. Generics (37:36)

The Swift language seems to be designed for generics. Optional types allow a variable to have a value or no value. This is similar in JavaScript to the undefined concept. OptionalValue signifies that the Swift enum can be made generic.

// Reimplement the Swift standard 
// library's optional type
enum OptionalValue<T> {
    case None
    case Some(T)
var maybeInt: OptionalValue<Int> = .None
maybeInt = .Some(100)

// Specialized Array
var letters: [String]
letters = ["a"]

Lots more! (40:52)

There’s a lot more to Swift language that couldn’t be covered: optionals, super-enums, structs, pattern matching, and runtime. All of these concepts are powerful and very useful when needed. Ultimately, differences between Swift and JavaScript boil down to API differences, along with the fact that Swift is compiled & has type safety. Swift does take similar concepts and features from JavaScript, such as its readability, syntax, and tooling.

Resources (Apple & elsewhere) (42:44)

Q&A (44:40)

Q: Were there anonymous functions being passed as arguments?
JP: Anonymous functions are basically just closures, one example of which was the sort function that takes in both the object to sort and an anonymous function to sort it by.

Q: What do you see as the future of Swift & Objective-C?
JP: I don’t see Objective-C as going away, but Apple will certainly prioritize Swift development.

Q: Are there any known performance differences? If so, how does that impact development?
JP: Swift is still work in progress, so its difficult to say if there are performance differences between Swift and Objective-C. From a design standpoint, it’s likely that Swift will be several orders of magnitude faster. It has the potential to be much faster but currently isn’t.

Q: Is Swift a subset of Objective-C? Is there anything we’ve lost in the transition?
JP: Yes, we’ve lost quite a few things, like the ability to have dynamic dispatch messaging, where we won’t know what a method will do until runtime. We must rethink things when porting to Swift. Most APIs haven’t changed, but there are a few things that are difficult to do in pure Swift.

Q: How easy is it to mix & match Objective-C and Swift?
JP: It is possible. For example, if you wanted to call Objective-C functions, methods, or classes from Swift or vice versa. The Swift IDE will auto-generate a header to bridge the two languages. It is still a work in progress so there is instability, but you can do a lot with that. Apple frameworks are still in Objective-C, so you can call most of them from Swift.

Q: Is Swift trying to encourage a culture of immutability & thread safety?
JP: Yes, almost certainly. Whenever possible, things should mostly be immutable unless necessary to be mutable. Such a culture wasn’t really possible to have in Objective-C.

Q: What’s the memory management model like in Swift?
JP: It does use ARC, Auto Reference Counting, which exists in both Swift and Objective-C. Both languages are retain-release languages, where you call retain to call ownership of an object and you call release when you are done with it. When retain is down to 0, the object can be destroyed. ARC does retain/release at compile time in Swift.

See full transcription

JP Simard

JP Simard

JP works at Realm on the Objective-C & Swift bindings, creator of jazzy (the documentation tool Apple forgot to release) and enjoys hacking on Swift tooling.