Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Slices of Swift

Slices of Swift

A few words about Swift
CocoaHeads, Krakow, Oct 30, 2014

Antonio Bello

November 05, 2014
Tweet

More Decks by Antonio Bello

Other Decks in Programming

Transcript

  1. Syntax Op#onal(semicolon var num = 10 var string = "String"

    Slices'of'Swi+','Antonio'Bello','@ant_bello 15
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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
  7. Crea%ng(Instances class User { ... } struct UserData { ...

    } var user = User() var userData = UserData() Slices'of'Swi+','Antonio'Bello','@ant_bello 30
  8. 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
  9. Op#onals Op#onals)replace: • nil • -1 • NSNotFound • [NSNull

    null] • ... Slices'of'Swi+','Antonio'Bello','@ant_bello 35
  10. 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
  11. 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
  12. 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
  13. 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
  14. 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
  15. 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
  16. What's'new Interoperability • id <==> AnyObject • NSString <==> String

    • NSArray <==> [AnyObject] • `NSDic(onary.<==>.[NSObject.:.AnyObject] Slices'of'Swi+','Antonio'Bello','@ant_bello 48
  17. 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
  18. 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
  19. 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
  20. 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
  21. 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
  22. 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
  23. 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
  24. 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
  25. 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
  26. 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