Tom MacWright

tom@macwright.com

Swift

Scratchpad & notes about Swift.

Comparison

SwiftJavaScript
Literal String
""
""
Literal Boolean
true, false
true, false
Null pointer
nil
null
Equality operator
==
== // comparison with type coercion
=== // strict comparison
Comments
/*
  * multi-line style
*/
// single line style
/*
  * multi-line style
*/
// single line style
Literal Array
[]
[]
Literal Object
[:]
{}
Reference to Owner
self.
this.
Debugging Print
print()
console.log()
String Interpolation
"Hello, \(tom)"
`Hello, ${tom}` // ES6 JavaScript only
Increment & decrement operators
none
++, --
Pushing onto an array
[1, 2].append(3)
[1, 2].push(3)
Concatentating arrays
[1, 2] + [3, 4]
[1, 2].concat([3, 4])
Counting for loop
for i in 0..<3 {
    print(i)
}
for (var i = 0; i < 3; i++) {
  console.log(i)
}
Function
func addTwo(a: Int, b: Int) -> Int {
  return a + b
}
// without types
function addTwo(a, b) {
  return a + b
}

// with Flow annotations
function addTwo(a: number, b: number): number {
  return a + b
}
Lambda
let myFunction = { $0 + $1 }
let myFunction = ($0, $1) => $0 + $1

Equivalents

SwiftJavaScript
HTTP RequestsAlamofire, PMHTTPrequest
ReduxReSwiftRedux

Declaring variables

In both Swift and JavaScript, let lets you assign a variable and bans future re-assignment to that variable. But in Swift, that value is also immutable. It’s helpful to think of Swift let as JavaScript const and Swift var as JS let.

let a = 0

// In swift, the following line will cause an error
let a = 1

// and this line is also wrong
a = a + 1
let a = 0

// In javascript, the following line will cause an error
let a = 1

// but this line will not. the value is mutable
a = a + 1