Top Banner
Swift Rocks! Anton Mironov Software Engineer at 1
80

Swift rocks! #1

Aug 18, 2015

Download

Technology

Hackraft
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Swift rocks! #1

Swift Rocks!

Anton Mironov Software Engineer at 1

Page 2: Swift rocks! #1

Everything started with

Low Level Virtual Machine

2

Page 3: Swift rocks! #1

Recent Objective-C features

• Blocks (closures)

• Automatic Reference Counting

• Literals

3

Page 4: Swift rocks! #1

Swift is a next next step

4

Page 5: Swift rocks! #1

Genius behind all of this

PhD Chris Lattner @clattner_llvm

5

Page 6: Swift rocks! #1

Swift is based on• Objective-C

• Haskel

• Ruby

• Python

• C#

• and many others

6

Page 7: Swift rocks! #1

First Lines of Code

print("Hello World!")

7

Page 8: Swift rocks! #1

First Lines of Code

print("\(name), I am your father")

8

Page 9: Swift rocks! #1

First Lines of Code

var name = "Luke" print("\(name), I am your father")

9

Page 10: Swift rocks! #1

First Lines of Code

var name = "Luke" let role = "father" print("\(name), I am your \(role)")

10

Page 11: Swift rocks! #1

Operators

let a = 3 let b = 4 let sum = a + b

11

Page 12: Swift rocks! #1

Operators

infix operator + { associativity left precedence 140 }

func +(lhs: Int, rhs: Int) -> Int

12

Page 13: Swift rocks! #1

No Autocasting

let a = 3 let b = 4.5 let sum = a + b

13

Page 14: Swift rocks! #1

No Autocasting

let a = 3 let b = 4.5 let sum = Double(a) + b

14

Page 15: Swift rocks! #1

Auto casting can be EvilNSEventModifierFlags modifierFlags = NSApp.currentEvent.modifierFlags;

BOOL isControlKeyPressed = modifierFlags & NSControlKeyMask;

if (isControlKeyPressed) { NSLog(@"Control pressed"); } else { NSLog(@"Control NOT pressed"); }

15

Page 16: Swift rocks! #1

Branching

if 0 == number % 2 { print("even") } else { print("odd") }

16

Page 17: Swift rocks! #1

Branching

let string = (0 == number % 2) ? "even" : "odd"

17

Page 18: Swift rocks! #1

Branchingswitch numberOfApples { case 0: return "none" case 6...10: return "just right" case 42, -1: return "let me see" case let value where (1 == value % 2): return "that's odd" default: return "this is unacceptable" } 18

Page 19: Swift rocks! #1

Collections: Array

let arrayOfInts = [5, 4, 3, 2, 1]

19

Page 20: Swift rocks! #1

Collections: Set

let setOfInts: Set<Int> = [ 5, 4, 3, 2, 1 ]

20

Page 21: Swift rocks! #1

Collections: Dictionary

let dictionaryOfNamesByDigit = [ 5: "five", 4: "four", 3: "three", 2: "two", 1: "one" ]

21

Page 22: Swift rocks! #1

Cycles: Precondition

var i = 0 while i < 5 { print("value \(i)") i++ }

22

Page 23: Swift rocks! #1

Cycles: Postcondition

var i = 0 repeat { print("value \(i)") i++ } while i < 5

23

Page 24: Swift rocks! #1

Cycles: Counter

for var i = 0; i < 5; i++ { print("value \(i)") }

24

Page 25: Swift rocks! #1

Cycles: Enumeration

let arrayOfInts = [5, 4, 3, 2, 1] for value in arrayOfInts { print("\(value)") }

25

Page 26: Swift rocks! #1

Objective-C: Null Object Pattern

id operation = nil; [operation start];

26

Page 27: Swift rocks! #1

Swift: Optionals

let operation: NSOperation? = nil operation?.start()

27

Page 28: Swift rocks! #1

Swift: Optionals

if nil != person { return "Hello \(person!)" } else { return "Hello to nobody" }

28

Page 29: Swift rocks! #1

Swift: Optionals

if let nonNullPerson = person { return "Hello \(nonNullPerson)" } else { return "Hello to nobody" }

29

Page 30: Swift rocks! #1

Swift is Great for Imperative Programming

30

Page 31: Swift rocks! #1

Functionsfunc name(args) -> ReturnType { … }

31

Page 32: Swift rocks! #1

Functions: named arguments

func buildMessageForPerson( person: String, role: String) -> String { return "\(name), I am your \(role)" }

let message = buildMessageForPerson("Luke", role: "father" )

32

Page 33: Swift rocks! #1

Functions: default valuesfunc buildMessageForPerson( person: String = "Luke", role: String) -> String { return "\(person), I am your \(role)" }

let message = buildMessageForPerson( role: "father" )

33

Page 34: Swift rocks! #1

Functions: multiple returnfunc divide( a: Int, _ b: Int ) -> (result: Int, modulo: Int) { return (a / b, a % b) }

let result = divide(11, 4).result let modulo = divide(11, 4).modulo

34

Page 35: Swift rocks! #1

Functions are First Class Citizen

35

Page 36: Swift rocks! #1

Functions as arguments Simple Example

func add(a: Int, b: Int) -> Int { return a + b } func mul(a: Int, b: Int) -> Int { return a * b }

func runMathOp(a: Int, _ b: Int, op: (Int, Int) -> Int ) -> Int { return op(a, b) }

let value1 = runMathOp(4, 3, op: add) let value2 = runMathOp(4, 3, op: mul)

36

Page 37: Swift rocks! #1

Functions as arguments Simple Example

func runMathOp(a: Int, _ b: Int, op: (Int, Int) -> Int ) -> Int { return op(a, b) }

let value1 = runMathOp(4, 3, op: +) let value2 = runMathOp(4, 3, op: -)

37

Page 38: Swift rocks! #1

Swift is Functional Language

38

Page 39: Swift rocks! #1

Imperative Stylelet names = ["Luke", "Chuwy", "Baker"] var messages = [String]()

for name in names { let message = buildMessageForPerson(name, "father") messages.append(message) }

print("\(messages)")

39

Page 40: Swift rocks! #1

Functional Stylelet names = ["Luke", "Chuwy", "Baker"] let messages = names.map { buildMessageForPerson($0, "father") }

print("\(messages)")

40

Page 41: Swift rocks! #1

Closuresfunc buildOperation(multiplier: Int ) -> (Int -> Int) { func multiply(value: Int) -> Int { return value * multiplier }

return multiply }

let operation = buildOperation(3) let value = operation(4)

41

Page 42: Swift rocks! #1

Just use Functional Paradigm

42

Page 43: Swift rocks! #1

Type System

43

Page 44: Swift rocks! #1

Type System Classification Criteria: Parameters Passing and Ownership• By Value let a = 3

• By Sharing (by reference to shared object) let userDefaults = NSUserDefaults.standardUserDefaults()

• By Reference let operation = myFunction let c = operation(a, b)

44

Page 45: Swift rocks! #1

Type System Classification Criteria: OOP

• Encapsulation

• Inheritance

• Polymorphism

45

Page 46: Swift rocks! #1

Type System Classification Criteria: Access Control

• Public - visible for importers

• Internal (default) - visible within module

• Private - visible within file

46

Page 47: Swift rocks! #1

Type System Classification Criteria: Objective-C compatibility• partial

• none

47

Page 48: Swift rocks! #1

Types• tuple

48

Page 49: Swift rocks! #1

Types• tuple

• function

49

Page 50: Swift rocks! #1

Classesclass Transport {

} 50

Page 51: Swift rocks! #1

Classesclass Transport { let name: String

} 51

Page 52: Swift rocks! #1

Classesclass Transport { let name: String private var velocity: Double = 0.0

} 52

Page 53: Swift rocks! #1

Classesclass Transport { let name: String private var velocity: Double = 0.0 init(name: String) { self.name = name }

} 53

Page 54: Swift rocks! #1

Classesclass Transport { let name: String private var velocity: Double = 0.0 init(name: String) { self.name = name } func beep() { print("Beep!") } } 54

Page 55: Swift rocks! #1

Classeslet transport = Transport( name: "kinda boat" )

55

Page 56: Swift rocks! #1

Classeslet transport = Transport( name: "kinda boat" ) transport.beep()

56

Page 57: Swift rocks! #1

Classeslet transport = Transport( name: "kinda boat" ) transport.beep() transport.speed = 10.0

57

Page 58: Swift rocks! #1

Classesclass Car: Transport { var color: String = "Red" }

58

Page 59: Swift rocks! #1

Classesclass Car: Transport, Paintable, Movable { var color: String = "Red"

… }

59

Page 60: Swift rocks! #1

Classes Strong Referenceclass Person { var transport: Transport }

60

Page 61: Swift rocks! #1

Classes Weak Referenceclass Car: Transport { weak var passanger: Passanger? }

61

Page 62: Swift rocks! #1

Classes Unowned Reference

class Node { unowned var parentNode: Node }

62

Page 63: Swift rocks! #1

Structuresstruct Point2D { var x: Double var y: Double

init(x: Double, y: Double) { self.x = x self.y = y } }

63

Page 64: Swift rocks! #1

Structuresvar point1 = Point2D(x: 1.0, y: 2.0) var point2 = point1 point1.x = 3.0

// (point1.x != point2.x)

64

Page 65: Swift rocks! #1

Structureslet point1 = Point2D(x: 1.0, y: 2.0) // point1 is immutable

65

Page 66: Swift rocks! #1

Structuresstruct Point2D { var x: Double var y: Double … mutating func multiply(

mult: Double) { self.x *= mult self.y *= mult } }

66

Page 67: Swift rocks! #1

Structures are everywhere• Int, Bool, UInt64, Float, Double, …

• String

• Array, Set, Dictionary

• …

67

Page 68: Swift rocks! #1

Enumsenum TokenStatus: String { case None = "none" case Valid = "valid" case Invalid = "invalid" case Expired = "expired"

var shouldRefetch: Bool { return .Valid == self } }

68

Page 69: Swift rocks! #1

Enums (Unions)enum FileSystemError: ErrorType { case InvalidURL(NSURL) case InvalidPermissions case UnknownErrorCode(Int) }

69

Page 70: Swift rocks! #1

Enums (Unions)switch fileSystemError { case .InvalidURL(let URL): print("Invalid URL \(URL)") case .InvalidPermissions: print("Invalid permissions") case .UnknownErrorCode(let code) where code == -150: print("I've seen this error somewhere") case .UnknownErrorCode(let code): print("Something gone very wrong \(code)") }

70

Page 71: Swift rocks! #1

Protocolsprotocol Drawable { var boundingRect: NSRect { get } func draw() }

struct Polygon: Drawable { var points = [NSPoint]() //MARK: Drawable var boundingRect: NSRect? { ... } func draw() { ... } } 71

Page 72: Swift rocks! #1

Generic Functionsfunc min<T: Comparable>( lhs: T, _ rhs: T ) -> T { return lhs < rhs ? lhs : rhs }

72

Page 73: Swift rocks! #1

Generic Typesstruct Point<T: FloatingPointType> { var x: T var y: T }

73

Page 74: Swift rocks! #1

Extensionsextension NSDate { var myBirthday: NSDate { … } }

74

Page 75: Swift rocks! #1

Protocols + Extensions + Generics = ❤

75

Page 76: Swift rocks! #1

Swift

Objective-C

76

Page 77: Swift rocks! #1

Simple or Complex?

77

Page 78: Swift rocks! #1

Swift on Prod

78

Page 79: Swift rocks! #1

Just use It!

79

Page 80: Swift rocks! #1

Thank you!

Anton Mironov Software Engineer at [email protected]

80