Share
Embed
Slices of Swift
A few words about Swift
CocoaHeads, Krakow, Oct 30, 2014
Antonio Bello
November 05, 2014
Transcript
63 slides
-
Swi$%is%s'll%not%stable • frequent)Xcode)crashes • Xcode)slowness • limita5ons)(expressions)with)max)5)opera5ons) • lack)of)some)features)(reflec5on) •
misleading)compiler)error)messages Slices'of'Swi+','Antonio'Bello','@ant_bello 7 -
How$Swi'$differs$from$Objec3ve$C • strongly*typed • no*dynamic*messaging • vtable:*sta5c*(compile*5me)*method*invoca5on • no*square*brackets*(newbies*will*appreciate) •
no*header*files Slices'of'Swi+','Antonio'Bello','@ant_bello 10 -
Syntax Op#onal(semicolon var num = 10 var string = "String"
Slices'of'Swi+','Antonio'Bello','@ant_bello 15 -
Syntax Semicolon)used)to)separate)statements)in)the) same)line var num = 10; var string =
"String" Slices'of'Swi+','Antonio'Bello','@ant_bello 16 -
Syntax No#parenthesis#in#control#flow#statements while condition == true { print("It's true") }
Slices'of'Swi+','Antonio'Bello','@ant_bello 17 -
Syntax Braces'required'in'control'flow'statements if swift == "new" { print("learn it") }
Slices'of'Swi+','Antonio'Bello','@ant_bello 18 -
Syntax switch!cases!with!autom-c!breaks!and!no! explicit!fallthrough var number: Int = 1 switch (number)
{ case 0: print("It's zero") case 1: print("It's 1") fallthrough default: print("It's not zero!") } Slices'of'Swi+','Antonio'Bello','@ant_bello 19 -
Variables:*mutable*and*immutable var!declares!a!mutable!variable var intNum = 5 intNum = 15 //
OK Slices'of'Swi+','Antonio'Bello','@ant_bello 20 -
Variables:*mutable*and*immutable let!declares!an!immutable!variable let intConst = 5 intConst = 15 //
ERROR!! Slices'of'Swi+','Antonio'Bello','@ant_bello 21 -
Type%inference Type%can%be%inferred%from%the%context var thisIsAnInt = 5 is#equivalent#to: var thisIsAnInt: Int
= 5 Slices'of'Swi+','Antonio'Bello','@ant_bello 23 -
Ini$aliza$on All#variables#and#proper/es#must#be#ini/alized let intImmutable: Int = 5 // OK var
intMutable = 5 // OK Slices'of'Swi+','Antonio'Bello','@ant_bello 24 -
Ini$aliza$on Op#onals)defaulted)to)nil var optionalInt: Int? // OK, nil by default
Slices'of'Swi+','Antonio'Bello','@ant_bello 25 -
Ini$aliza$on Mutable(variables(support(deferred(ini2aliza2on var mutableInt: Int ... // Code not using
mutableInt mutableInt = 5 // OK Slices'of'Swi+','Antonio'Bello','@ant_bello 26 -
Ini$aliza$on Immutable)must)be)ini-alized)inline let immutableInt: Int = 10 // OK let
immutableInt: Int // ERROR Slices'of'Swi+','Antonio'Bello','@ant_bello 27 -
Func%ons(and(methods Objec&ve(C - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { ...
} Swi$ func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { ... } Slices'of'Swi+','Antonio'Bello','@ant_bello 28 -
Func%ons(and(methods • func&ons)have)no)external)names)by)default • methods)have)implicit)external)names)a8er)the)first)parameter • ini&alizers)have)implicit)external)names)for)all)parameters • external)names)can)be)disabled)by)prefixing)with)_ •
external)names)can)be)defaulted)to)local)names)with)# Slices'of'Swi+','Antonio'Bello','@ant_bello 29 -
Crea%ng(Instances class User { ... } struct UserData { ...
} var user = User() var userData = UserData() Slices'of'Swi+','Antonio'Bello','@ant_bello 30 -
Closures Objec&veC ^BOOL(User *user, NSError *error) { return error !=
nil } Swi$ { (user: User, error: NSError?) -> Bool in return error != nil } Slices'of'Swi+','Antonio'Bello','@ant_bello 31 -
Op#onals • Indicates+absence+of+value • implemented+as+Optional<T>+enum • syntac5cally+sugared • usable'for'value'and'reference'types •
actual+values+must+be+unwrapped+from+op5onals Slices'of'Swi+','Antonio'Bello','@ant_bello 34 -
Op#onals Op#onals)replace: • nil • -1 • NSNotFound • [NSNull
null] • ... Slices'of'Swi+','Antonio'Bello','@ant_bello 35 -
Op#onals Important)to)remember op#onals(are(enums enum Optional<T> { case None case Some(T)
} Slices'of'Swi+','Antonio'Bello','@ant_bello 37 -
Op#onals Terms&frequently&used: • unwrapping:+? • forced+unwrapping:+! • implicitly+unwrapped:+! • op5onal+binding:+if
let x = x { • op5onal+chaining:+user?.address?.street Slices'of'Swi+','Antonio'Bello','@ant_bello 38 -
What's'new Type%Inference The$type$of$a$variable$can$be$inferred var intNum = 5 var string =
"I'm a string, not an Int" Slices'of'Swi+','Antonio'Bello','@ant_bello 40 -
What's'new Tuples • A#tuple#is#a#compound#value,#or#anonymous#struct let result = (404, "NotFound") •
Different)types)can)be)mixed • Can)be)passed)as)arguments)to)func8ons Slices'of'Swi+','Antonio'Bello','@ant_bello 41 -
What's'new Tuples • Can$be$returned$by$func.ons func() -> (User?, NSError?) { ...
return (user, error) } let (user, error) = func() Slices'of'Swi+','Antonio'Bello','@ant_bello 42 -
What's'new Generics Make%a%class%class%independent%from%the%type%it%manages class Tree<T> { var tree: T ...
} Slices'of'Swi+','Antonio'Bello','@ant_bello 43 -
What's'new Generics It#works#with#structs#and#enums#as#well struct Array<T> { ... } struct Dictionary<T>
{ ... } enum Optional<T> { case None case Some(T) } Slices'of'Swi+','Antonio'Bello','@ant_bello 44 -
What's'new Generics It#works#with#func/ons#and#methods func printToConsole<T: Printable>(printable: T) { print(printable.description) }
Slices'of'Swi+','Antonio'Bello','@ant_bello 45 -
What's'new Collec&on(Types • Array<T> • Dictionary<T, V> var array: Array<String>
= ["1", "2", "3"] var array: [String] = ["1", "2", "3"] var dict: Dictionary<String, Int> = ["1": 100, "2": 200, "3": 300] var dict: [String : Int] = ["1": 100, "2": 200, "3": 300] Slices'of'Swi+','Antonio'Bello','@ant_bello 46 -
What's'new Interoperability • id <==> AnyObject • NSString <==> String
• NSArray <==> [AnyObject] • `NSDic(onary.<==>.[NSObject.:.AnyObject] Slices'of'Swi+','Antonio'Bello','@ant_bello 48 -
What's'new Operator(Overloading Redefine&an&exis+ng&unary&or&binary&operator prefix func ++<T>(inout lhs: Array<T>) { if
lhs.count > 0 { lhs.append(lhs.last!) } } var array = [1, 2, 3, 4] ++array // = [1, 2, 3, 4, 4] Slices'of'Swi+','Antonio'Bello','@ant_bello 49 -
What's'new Custom'operators Define%a%brand%new%operator infix operator <%> {} func <%>(dividend: Int,
divisor: Int) -> (quotient: Int, remainder: Int) { let quotient = dividend / divisor let remainder = dividend - quotient * divisor return (quotient, remainder) } let (q, r) = 17 <%> 3 // q = 5, r = 2 Slices'of'Swi+','Antonio'Bello','@ant_bello 50 -
What's'new Subscripts:+[] • Syntac(c)sugar)for)accessing)class/struct)members • Can)take)any)number)of)arguments)of)any)type • Used)in)Array)and)Dictionary let dict
= ["cat": "black", "dog": "brown"] let cat = dict["cat"] Slices'of'Swi+','Antonio'Bello','@ant_bello 51 -
What's'new Subscripts class Matrix<T> { var matrix: Array<T> var numColumns:
Int var numRows: Int ... subscript(row: Int, col: Int) -> T { get { return self.matrix[row * self.numColumns + col] } set { self.matrix[row * self.numColumns + col] = newValue } } } Slices'of'Swi+','Antonio'Bello','@ant_bello 52 -
What's'new Type%Aliases Define%an%alias%for%a%type typealias Latitude = Float typealias Longitude =
Float typealias ArrayOfString = [String] typealias Response = (response: HttpResponse, error: NSError?) -> Void Slices'of'Swi+','Antonio'Bello','@ant_bello 53 -
What's'new Nil$Coalescing$Operator Binary'operator'evalua/ng'and'returning'the'result'of'the'le5' expression,'if'not'nil,'otherwise'the'result'of'the'right'expression var color: UIColor? = UIColor.redColor() ...
color = nil ... var selectedColor = color ?? UIColor.blackColor() Slices'of'Swi+','Antonio'Bello','@ant_bello 54 -
What's'new Range&Operators Half%Open*range*operator var array = [10, 20, 30, 40,
50] for index in 0..<array.count { print(array[index]) } Closed'range'operator for elementNumber in 1...array.count { print("This is the element no. \(elementNumber):" + "\(array[elementNumber - 1])") } Slices'of'Swi+','Antonio'Bello','@ant_bello 55 -
What's'new Nested&Comments 1 /* 2 /** 3 this is the
main loop 4 **/ 5 for elementNumber in 1...array.count { 6 7 /* Prints the element # and its value */ 8 print("This is the element no. \(elementNumber):" + 9 "\(array[elementNumber - 1])") 10 11 // No return value here 12 } 13 */ Slices'of'Swi+','Antonio'Bello','@ant_bello 56 -
What's'new Curried'Func+ons Used%to%translate%a%func/on%taking%a%tuple%of%arguments%into%a% sequence%of%func/ons,%each%one%taking%one%argument func normal(a: Int, b: String, c:
Int) -> Float let result = normal(4, "string", 7) func curried(a: Int)(b: String)(c: Int) -> Float let fa = curried(4) // Returns a function accepting a parameter of type `String` let fb = fa("string") // Returns a function accepting a parameter of type `Int` let result = fb(7) // Returns a `Float` Slices'of'Swi+','Antonio'Bello','@ant_bello 57 -
What's'new Curried'Func+ons struct User { var name: String var email:
String var age: Int init(name: String, email: String, age: Int) { ... } static func create(name: String)(email: String)(age: Int) -> User { return User(name: name, email: email, age: age) } } let name = "User Name" let email = "[email protected]" let age = 33 let user = User.create(name: name)(email: email)(age: age) Slices'of'Swi+','Antonio'Bello','@ant_bello 58 -
What's'new Curried'Func+ons We#can#turn#this: let json: [String : AnyObject] = ...
let name = json["name"] if let name = JsonString(name) { let email = json["email"] if let email = JsonString(email) { let age = json["age"] if let age = JsonInt(age) { let user = User(name: name, email: email, age: age) } } } Slices'of'Swi+','Antonio'Bello','@ant_bello 60 -
What's'new Curried'Func+ons into%this: static func create(name: String)(email: String)(age: Int) ->
User let user = User.create <^> json["name"] >>> JsonString <&&> json["email"] >>> JsonString <&&> json["age"] >>> JsonInt Slices'of'Swi+','Antonio'Bello','@ant_bello 61