ten-page brief overview of swift for scala developers
DESCRIPTION
This is a ten-page brief overview document about Apple's brand new Swift programming language. This document is written in a Scala developer's view, so many advanced Swift features which do not have proper counterparts in Scala were baldly omitted. However, if you want to get a feeling that how Swift looks like, this is a perfect starter.TRANSCRIPT
Ten-page Brief Overview of Swift for Scala Developers
Heejong Lee @heejongl
June 10, 2014
Disclaimers
• This slide is for introducing Swift from Scala developer’s view
• Since two languages are not semantically equal, some pairs may not be directly interchangeable with each other.
• But, still, they (the each pair) are similar in their practical usage
Variable Declarations
let x = 1 val x = 1
Swift Scala
Immutable
var x = 1 var x = 1Mutable
let x: Int = 1 val x: Int = 1Type annotation
Built-in Types
Int Int
Swift Scala
Integer
Bool BooleanBoolean
Double DoubleDouble
Int -> Int Int => IntFunction
Int? Option[Int]Option
User-defined Types
class X {} class X {}
Swift Scala
class
struct X {} class X() extends AnyValvalue class
enum A { case X(Int) } case class X(i: Int)immutable class
enum A { case X } case object Xsingleton class
User-defined Types
protocol X {} trait X {}
Swift Scala
Trait
extension X: Y {} implicit def a(x: X): ZPimp My Library
(class Z extends Y)
Function Declarations
func x() -> Int {}
def x() : Int = {}
Swift Scala
Method
{ (x: Int) in return x + 1}
{ x: Int => x + 1}
Closure
Placeholder{ $0 + $1 } { _ + _ }
Collection Declarations
[1,2,3] List(1,2,3)
Swift Scala
Sequence
[“x”: 1, “y”: 2] {“x”->1, “y”->2}Map
String interpolation“hello \(x)” “hello ${x}”
Collection Usage (sequence)
var x = [1,2,3]x.append(4); x List(1,2,3) :+ 4
Swift Scala
Add
x[0] x(0)Access
Mapx.map{$0 + 1} x.map{_ + 1}
Pattern Matching
switch x {case .Seoul: println("seoul")case .Tokyo: println("tokyo")default: println("others")}
x match {case Seoul => println("seoul")case Tokyo => println("tokyo")case _ => println("others")}
Swift Scala
exact match
switch x {case let .Seoul(y): println(y)case let .Tokyo(y): println(y)default: println("others")}
x match {case Seoul(y) => println(y)case Tokyo(y) => println(y)case _ => println("others")}
binding
switch a {case let (x,y) where x == y: println(x)case let (x,y): println("others")}
a match {case (x,y) if x == y => println(x)case (x,y) => println("others")}
conditional
Generics
func x<T>(a: T) def x[T](a: T)
Swift Scala
Generic method
class X<T> {} class X[T] {}Generic class
class X<T:U> {} class X[T<:U] {}Upper bound
Option Idiom
Optional(1) Option(1)
Swift Scala
Generator
(x?.map{$0+1})?.map{$0+1} x.flatMap{y=>Some(y.map{_+1})}Chaining
if let x = optValue { println(1)} else { println(2)}
optValue match { case Some(x) => println(1) case None => println(2)}
Extract