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

Deep Dive Into Swift

Deep Dive Into Swift

Deep Dive Into Swift presented at Cofee@DBG

Sarath C

April 01, 2015
Tweet

More Decks by Sarath C

Other Decks in Programming

Transcript

  1. Chris Lattner • Author of the original LLVM tool chain

    project • Started working on Swift in 2010 • A research intern at Microsoft Research • Leads Development Tool Effort at Apple
  2. – The RedMonk Programming Language Rankings: January 2015 “Swift has

    gone from our 68th ranked language during Q3 to number 22 this quarter, a jump of 46 spots.”
  3. enum CompassPoint { case North case South case East case

    West } var directionToHead = CompassPoint.East; directionToHead = .East;
  4. enum CompassPoint { case North case South case East case

    West } var directionToHead = CompassPoint.East; directionToHead = .East; switch(directionToHead) { case .East: println( "Heading east") case .West: println( "Heading West") case .North: println( "Heading North") case .South: println( "Heading South") default: println("Nowhere to go") }
  5. Enumerations can store associated values of any given type. The

    type can be different for each member in the enumeration
  6. // Associated Values Examples enum Barcode { case UPCA(Int, Int,

    Int, Int) case QRCode(String) } var productBarcode = Barcode.UPCA(8, 85909, 51226, 3) productBarcode = .QRCode("ABCDEFGHIJ")
  7. // Associated Values Examples enum Barcode { case UPCA(Int, Int,

    Int, Int) case QRCode(String) } var productBarcode = Barcode.UPCA(8, 85909, 51226, 3) productBarcode = .QRCode("ABCDEFGHIJ") let numberSystem = 8, manufacturer = 85909, product = 51226, check = 3 switch productBarcode { case let .UPCA(numberSystem, manufacturer, product, check) println("UPCA Detected") case let .QRCode("ABCDEFGHIJ") println("QRCode detected") }
  8. // Pattern Matching with Switch-Case let x = 9 switch(x)

    { case 1...5: // Closed range operator println( "Range - 1,2,3,4,5") case 6..<10: // Half closed range operator println( "Range - 6,7,8,9") default: println("Default") }
  9. Lazy Stored Properties • Initializes on first time access •

    Declared with lazy keyword • Lazy Stored properties can’t be a constant; for obvious reasons • Useful when the initial values are depends on outside factors
  10. // Lazy initialization class DataImporter { } class DataManager {

    lazy var importer = DataImporter() var data = [String]() } let m = DataManager() // importer has not yet been created m.data.append("Element 1"); m.data.append("Element 2"); m.data.append("Element 3"); // Initialize on first access m.importer.import();
  11. // Computed properties class Rectangle { var height = 0

    var width = 0 var area : Int { get { return height * width } } }
  12. // Property Observers class Temperature { var current : Int

    = 26 { willSet { println("\(newValue)"); // Prints 32 } didSet { println("\(oldValue)"); // Prints 26 } } } var obj = Temperature() obj.current = 32;
  13. Closures // Closures var cities = ["New Delhi", "Trivandrum", "Kochi",

    "Bangalore"] // Sort with delegates cities.sort({ (a, b) -> Bool in a < b })
  14. Closures - Trailing spaces // Closures var cities = ["New

    Delhi", "Trivandrum", "Kochi", "Bangalore"] // Sort with delegates cities.sort({ (a, b) -> Bool in a < b })
  15. Closures - Parentheses // Closures var cities = ["New Delhi",

    "Trivandrum", "Kochi", "Bangalore"] // Sort with delegates cities.sort { (a, b) -> Bool in a < b }
  16. Closures - Type inference // Closures var cities = ["New

    Delhi", "Trivandrum", "Kochi", "Bangalore"] // Sort with delegates cities.sort { (a, b) -> Bool in a < b }
  17. Closures - Type inference // Closures var cities = ["New

    Delhi", "Trivandrum", "Kochi", "Bangalore"] // Sort with delegates cities.sort { a, b -> Bool in a < b }
  18. Closures - Implicit return // Closures var cities = ["New

    Delhi", "Trivandrum", "Kochi", "Bangalore"] // Sort with delegates cities.sort { a, b in a < b }
  19. Closures - Positional Parameters // Closures var cities = ["New

    Delhi", "Trivandrum", "Kochi", "Bangalore"] // Sort with delegates — Positional parameters cities.sort { $0 < $1 }
  20. Closures - Operator as closure // Closures var cities =

    ["New Delhi", "Trivandrum", "Kochi", "Bangalore"] // Sounds interesting? cities.sort( < )
  21. var age : Int? age = response.parse() let x =

    age! // Your program would crash if you unwrap a nil value
  22. class Person { var residence : Residence? } class Residence

    { var address : Address? } class Address { var buildingNumber : String? var streetName : String? var apartmentNumber : String? }
  23. // Optional Binding if let home = paul.residence { if

    let postalAddress = home.address { if let building = postalAddress.buildingNumber { // Code } } }
  24. // optional chaining + bind + unwrap if let buildingNumber

    = paul.residence?.address?.buildingNumber { }
  25. designated initializers are primary initializers of a class a class

    must have at least one designated initializer classes tend to have few designated initializers
  26. class Food { var name: String // Designated Initializer init(name:

    String) { self.name = name } // Convenience Initializer convenience init() { self.init(name: "Unnamed") } }
  27. class Food { var name: String // Designated Initializer init(name:

    String) { self.name = name } // Convenience Initializer convenience init() { self.init(name: "Unnamed") } }
  28. class Food { var name: String // Designated Initializer init(name:

    String) { self.name = name } // Convenience Initializer convenience init() { self.init(name: "Unnamed") } }
  29. class Vehicle { let numberOfWheels = 0 } class Bicycle

    : Vehicle { override init() { super.init() numberOfWheels = 2 } } class Car : Vehicle { override init() { super.init() numberOfWheels = 4 } }
  30. class Vehicle { let numberOfWheels = 0 } class Bicycle

    : Vehicle { override init() { super.init() numberOfWheels = 2 } } class Car : Vehicle { override init() { super.init() numberOfWheels = 4 } }
  31. class Vehicle { let numberOfWheels = 0 } class Bicycle

    : Vehicle { override init() { super.init() numberOfWheels = 2 } } class Car : Vehicle { override init() { super.init() numberOfWheels = 4 } }
  32. class Vehicle { let numberOfWheels = 0 } class Bicycle

    : Vehicle { override init() { super.init() numberOfWheels = 2 } } class Car : Vehicle { override init() { super.init() numberOfWheels = 4 } }
  33. // Extension as instance method extension Int { func plusOne()

    -> Int { return self + 1 } } var i = 5 i.plusOne() 10.plusOne()
  34. // Extension as instance method extension Int { func plusOne()

    -> Int { return self + 1 } } var i = 5 i.plusOne() 10.plusOne()
  35. // Extension as instance method extension Int { func plusOne()

    -> Int { return self + 1 } } var i = 5 i.plusOne() 10.plusOne()
  36. // Extension as property extension Double { var km :

    Double { return self*1000.0 } var m : Double { return self } var cm : Double { return self / 100.0 } var mm : Double { return self / 10000.0 } var ft : Double { return self / 3.28084 } } let threeFeet = 3.ft // Meters let oneInch = 25.4.mm // Meters
  37. // Extension as property extension Double { var km :

    Double { return self*1000.0 } var m : Double { return self } var cm : Double { return self / 100.0 } var mm : Double { return self / 10000.0 } var ft : Double { return self / 3.28084 } } let threeFeet = 3.ft // Meters let oneInch = 25.4.mm // Meters
  38. // Extension as property extension Double { var km :

    Double { return self*1000.0 } var m : Double { return self } var cm : Double { return self / 100.0 } var mm : Double { return self / 10000.0 } var ft : Double { return self / 3.28084 } } let threeFeet = 3.ft // Meters let oneInch = 25.4.mm // Meters
  39. // Extension as class method extension UIColor { class func

    chilliRed() -> UIColor { return UIColor(red: 94/255, green: 25/255, blue: 33/255, alpha: 1) } } var chilliRed = UIColor.chilliRed()
  40. // Extension as class method extension UIColor { class func

    chilliRed() -> UIColor { return UIColor(red: 94/255, green: 25/255, blue: 33/255, alpha: 1) } } var chilliRed = UIColor.chilliRed()
  41. // Extension as class method extension UIColor { class func

    chilliRed() -> UIColor { return UIColor(red: 94/255, green: 25/255, blue: 33/255, alpha: 1) } } var chilliRed = UIColor.chilliRed()
  42. protocol LoginProtocol { func loginSuccessful() func loginFailed() } class ViewController

    : LoginProtocol { func loginFailed() { // code } func loginSuccessful() { // code } }
  43. protocol LoginProtocol { var someProperty : Int { get set

    } func loginSuccessful() func loginFailed() } class ViewController : LoginProtocol { func loginFailed() { // code } func loginSuccessful() { // code } var someProperty : Int = 0 { willSet { // Update UI with newValue } didSet { // code } } }
  44. protocol LoginProtocol { var someProperty : Int { get set

    } func loginSuccessful() func loginFailed() } class ViewController : LoginProtocol { func loginFailed() { // code } func loginSuccessful() { // code } var someProperty : Int = 0 { willSet { // Update UI with newValue } didSet { // code } } }
  45. protocol LoginProtocol { var someProperty : Int { get set

    } func loginSuccessful() func loginFailed() } class ViewController : LoginProtocol { func loginFailed() { // code } func loginSuccessful() { // code } var someProperty : Int = 0 { willSet { // Update UI with newValue } didSet { // code } } }
  46. protocol LoginProtocol { var someProperty : Int { get set

    } func loginSuccessful() func loginFailed() } class ViewController : LoginProtocol { func loginFailed() { // code } func loginSuccessful() { // code } var someProperty : Int = 0 { willSet { // Update UI with newValue } didSet { // code } } }
  47. func swapInt(inout a:Int, inout b:Int) { let t = a;

    a = b; b = t } func swapString(inout a:String, inout b:String) { let t = a; a = b; b = t } var a = 10, b = 20 swapInt(&a, &b) var p = "iOS 7", q = "iOS 8" swapString(&p,&q)
  48. func swapInt(inout a:Int, inout b:Int) { let t = a;

    a = b; b = t } func swapString(inout a:String, inout b:String) { let t = a; a = b; b = t } var a = 10, b = 20 swapInt(&a, &b) var p = "iOS 7", q = "iOS 8" swapString(&p,&q) // MARK: With Generics func Swap <T> (inout a: T, inout b: T) { let t = a; a = b; b = t } Swap(&a, &b); Swap(&p, &q);
  49. func swapInt(inout a:Int, inout b:Int) { let t = a;

    a = b; b = t } func swapString(inout a:String, inout b:String) { let t = a; a = b; b = t } var a = 10, b = 20 swapInt(&a, &b) var p = "iOS 7", q = "iOS 8" swapString(&p,&q) // MARK: With Generics func Swap <T> (inout a: T, inout b: T) { let t = a; a = b; b = t } Swap(&a, &b); Swap(&p, &q);
  50. // Generic Type struct Stack<T> { var items = [T]()

    mutating func push(item: T) { items.append(item) } mutating func pop() -> T { return items.removeLast() } }
  51. // Stack from somewhere class Stack<T> { } // Extension

    extension Stack { func top() -> T? { return nil } }
  52. // Type constraints func findIndex<T: Equatable>( array: [T], valueToFind: T)

    -> Int? { for(index, value) in enumerate(array) { if value == valueToFind { return index } } return nil }
  53. Structures and enumerations are value types. By default, the properties

    of a value type cannot be modified from within its instance methods.
  54. // Immutatbility and Mutating struct Point { var x =

    0.0, y = 0.0 // No change in the actual object func pointByScaling(factor: Double) -> Point { return Point(x: self.x*factor, y: self.y*factor) } // Function modifies the object mutating func scale(factor : Double) { self.x *= factor self.y *= factor } }
  55. // Immutatbility and Mutating struct Point { var x =

    0.0, y = 0.0 // No change in the actual object func pointByScaling(factor: Double) -> Point { return Point(x: self.x*factor, y: self.y*factor) } // Function modifies the object mutating func scale(factor : Double) { self.x *= factor self.y *= factor } }
  56. // Immutatbility and Mutating struct Point { var x =

    0.0, y = 0.0 // No change in the actual object func pointByScaling(factor: Double) -> Point { return Point(x: self.x*factor, y: self.y*factor) } // Function modifies the object mutating func scale(factor : Double) { self.x *= factor self.y *= factor } }
  57. struct Vector2D { var x = 0.0, y = 0.0

    } func + (left:Vector2D, right:Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y + right.y) } // Compound Operator func += (inout left:Vector2D, right:Vector2D) { left.x += right.x left.y += right.y } var vector = Vector2D(x: 3.0, y: 1.0) let anotherVector = Vector2D(x: 2.0, y: 4.0) let combinedVector = vector + anotherVector vector += anotherVector
  58. struct Vector2D { var x = 0.0, y = 0.0

    } func + (left:Vector2D, right:Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y + right.y) } // Compound Operator func += (inout left:Vector2D, right:Vector2D) { left.x += right.x left.y += right.y } var vector = Vector2D(x: 3.0, y: 1.0) let anotherVector = Vector2D(x: 2.0, y: 4.0) let combinedVector = vector + anotherVector vector += anotherVector
  59. struct Vector2D { var x = 0.0, y = 0.0

    } func + (left:Vector2D, right:Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y + right.y) } // Compound Operator func += (inout left:Vector2D, right:Vector2D) { left.x += right.x left.y += right.y } var vector = Vector2D(x: 3.0, y: 1.0) let anotherVector = Vector2D(x: 2.0, y: 4.0) let combinedVector = vector + anotherVector vector += anotherVector
  60. struct Vector2D { var x = 0.0, y = 0.0

    } func + (left:Vector2D, right:Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y + right.y) } // Compound Operator func += (inout left:Vector2D, right:Vector2D) { left.x += right.x left.y += right.y } var vector = Vector2D(x: 3.0, y: 1.0) let anotherVector = Vector2D(x: 2.0, y: 4.0) let combinedVector = vector + anotherVector vector += anotherVector
  61. struct Vector2D { var x = 0.0, y = 0.0

    } // Custom operator - Doubling prefix operator +++ {} prefix func +++ (inout vector: Vector2D) -> Vector2D { vector += vector return vector } let doubled = +++vector
  62. struct Vector2D { var x = 0.0, y = 0.0

    } // Custom operator - Doubling prefix operator +++ {} prefix func +++ (inout vector: Vector2D) -> Vector2D { vector += vector return vector } let doubled = +++vector
  63. struct Vector2D { var x = 0.0, y = 0.0

    } // Custom operator - Doubling prefix operator +++ {} prefix func +++ (inout vector: Vector2D) -> Vector2D { vector += vector return vector } let doubled = +++vector
  64. References • The Swift Programming Language - iBooks • Using

    Swift with Objective-C and Cocoa - iBooks • WWDC 2014 Sessions on Swift • Developing iOS 8 Apps with Swift - iTunesU - Stanford