Concepts of programming languages Swift Lukas, Anvar, Roald, Bart, - - PowerPoint PPT Presentation

concepts of programming languages
SMART_READER_LITE
LIVE PREVIEW

Concepts of programming languages Swift Lukas, Anvar, Roald, Bart, - - PowerPoint PPT Presentation

Concepts of programming languages Swift Lukas, Anvar, Roald, Bart, Lars [Faculty of Science Information and Computing Sciences] 1 Birth of a new language Swift isnt it beautiful? Developed in secret [Faculty of Science Information


slide-1
SLIDE 1

[Faculty of Science Information and Computing Sciences] 1

Concepts of programming languages

Swift

Lukas, Anvar, Roald, Bart, Lars

slide-2
SLIDE 2

[Faculty of Science Information and Computing Sciences] 2

Birth of a new language

Swift… isn’t it beautiful?

◮ Developed in secret

slide-3
SLIDE 3

[Faculty of Science Information and Computing Sciences] 3

Birth of a new language

Swift… isn’t it beautiful?

◮ Developed in secret ◮ Successor of Objective-C

slide-4
SLIDE 4

[Faculty of Science Information and Computing Sciences] 4

Objective C

◮ Introduced by NeXT

Figure 1: Steve Jobs

slide-5
SLIDE 5

[Faculty of Science Information and Computing Sciences] 5

Objective C

◮ Introduced by NeXT

Figure 2: Steve Jobs

slide-6
SLIDE 6

[Faculty of Science Information and Computing Sciences] 6

Objective C

◮ Introduced by NeXT ◮ Widely used after fjrst iPhone

slide-7
SLIDE 7

[Faculty of Science Information and Computing Sciences] 7

Objective C

◮ Introduced by NeXT ◮ Widely used after fjrst iPhone ◮ Steep learning curve

slide-8
SLIDE 8

[Faculty of Science Information and Computing Sciences] 8

Objective C

Objective-C: NSString *myString = @"Goodmorning"; NSString *test = [myString stringByAppendingString:@" Wouter"]; Python: myString = "Goodmorning"; test = myString + " Wouter";

slide-9
SLIDE 9

[Faculty of Science Information and Computing Sciences] 9

Swift

Apple came to the rescue and developed Swift!

◮ Inferred typing

slide-10
SLIDE 10

[Faculty of Science Information and Computing Sciences] 10

Swift - Inferred typing

Normal: var Str : String = "hallo" var Dbl : Double = 3.14 Inferred: var Str = "hallo" //string var Dbl = 3.14 //double

slide-11
SLIDE 11

[Faculty of Science Information and Computing Sciences] 11

Swift - Inferred typing

Though Swift allows inferred typing it is still static typed

slide-12
SLIDE 12

[Faculty of Science Information and Computing Sciences] 12

Swift

Apple came to the rescue and developed Swift!

◮ Inferred typing ◮ Neat Closures

slide-13
SLIDE 13

[Faculty of Science Information and Computing Sciences] 13

Swift - Closures

Without closures: func sorting(_ s1: String, _ s2: String) -> Bool { return s1 < s2 } var reversedNames = names.sorted(by: sorting) With closures: var reversedNames = names.sorted { return s1 < s2 }

slide-14
SLIDE 14

[Faculty of Science Information and Computing Sciences] 14

Swift

Apple came to the rescue and developed Swift!

◮ Inferred typing ◮ Neat Closures ◮ Protocols

slide-15
SLIDE 15

[Faculty of Science Information and Computing Sciences] 15

Swift - Pass by value or reference

Protocols are passed by value. In Swift everything except for Classes is passed by value

slide-16
SLIDE 16

[Faculty of Science Information and Computing Sciences] 16

Swift

Apple came to the rescue and developed Swift!

◮ Inferred typing ◮ Neat Closures ◮ Protocols ◮ Generics

slide-17
SLIDE 17

[Faculty of Science Information and Computing Sciences] 17

Swift

Get length of generic type func <T: count>length(_ variable: T) -> Int { return variable.count }

slide-18
SLIDE 18

[Faculty of Science Information and Computing Sciences] 18

Swift

Comparison with OO languages

slide-19
SLIDE 19

[Faculty of Science Information and Computing Sciences] 19

Parameterless function

◮ Functions are the fjrst-class citizens in both C# and Swift; // Parameterless With Return Value - C# string sayHello() { return "Hello!"; } // Parameterless With Return Value - Swift func sayHello() -> String { return "Hello!" }

slide-20
SLIDE 20

[Faculty of Science Information and Computing Sciences] 20

Function with Parameters

// C# string sayHello(string name) { // do something } // Swift func sayHello(name: String) -> String { // do something }

slide-21
SLIDE 21

[Faculty of Science Information and Computing Sciences] 21

Multiple Return Values

// C# - using a Struct struct Person { public string firstName; public string lastName; } Person getPerson() { return new Person { firstName = "Bill", lastName = "Gates" }; }

slide-22
SLIDE 22

[Faculty of Science Information and Computing Sciences] 22

Multiple Return Values

// Swift func getPerson() -> (firstName: String, lastName: String) { return ("Steve", "Jobs") }

slide-23
SLIDE 23

[Faculty of Science Information and Computing Sciences] 23

Function Parameter Name Alias

// External Parameter Names // C# // no equivalent exists // Swift func combineName(firstName first: String, lastName last: String) { // accessing the parameters can be done by referencing // "first" and "last" respectively return first + " " + last; }

slide-24
SLIDE 24

[Faculty of Science Information and Computing Sciences] 24

Function Types

// C# int add (int a, int b) { return a + b; } Func<int, int, int> doMath = add; var total = doMath(19, 23);

slide-25
SLIDE 25

[Faculty of Science Information and Computing Sciences] 25

Function Types

// Swift func add(a: Int, b: Int) -> Int { return a + b } var doMath: (Int, Int) -> Int = add var total = doMath(19, 23)

slide-26
SLIDE 26

[Faculty of Science Information and Computing Sciences] 26

Nested Functions

// C# int doSomething(int a, int b) { var add = new Func<int, int, int>( (first, second) => { return first + second; } ); return add(a,b); }

slide-27
SLIDE 27

[Faculty of Science Information and Computing Sciences] 27

Nested Functions

// Swift func doSomething(a: Int, b: Int) -> Int { func add(first: Int, second: Int) -> Int { return first + second } return add(a, b) }

slide-28
SLIDE 28

[Faculty of Science Information and Computing Sciences] 28

Swift

Optionals

slide-29
SLIDE 29

[Faculty of Science Information and Computing Sciences] 29

Optionals

What are Optionals? * Contains a value of some type or nil * Similar to Maybe in Haskell

slide-30
SLIDE 30

[Faculty of Science Information and Computing Sciences] 30

Optionals

How do we use Optionals? let shortForm: Int? = Int("42") let longForm: Optional<Int> = Int("42")

slide-31
SLIDE 31

[Faculty of Science Information and Computing Sciences] 31

Optionals

So why are they awesome?

slide-32
SLIDE 32

[Faculty of Science Information and Computing Sciences] 32

Optional Binding

if let myLifesPurpose: String = Optional.none { print("its something: \(myLifesPurpose)") } else { print("guess ill die") }

slide-33
SLIDE 33

[Faculty of Science Information and Computing Sciences] 33

Optional Chaining

class SteamId { var id = "xXx_360n0Sc0P3_xXx"} class MacUser { var steamacc:SteamId?} let wouterSwierstra = MacUser() let id = wouterSwierstra.steamacc?.id print(id) // prints nil let id2 = wouterSwierstra.steamacc?.id ?? "Y U HAVE NO STEAM?" print(id2) // prints Y U HAVE NO STEAM?

slide-34
SLIDE 34

[Faculty of Science Information and Computing Sciences] 34

Laziness

◮ Not standard in Swift ◮ keyword lazy ◮ more cumbersome to do than in Haskell

slide-35
SLIDE 35

[Faculty of Science Information and Computing Sciences] 35

Laziness

class Probe { init() { print("YOU MUST CONSTRUCT ADDITIONAL PYLONS.") } } class Protoss { lazy var builder = Probe() } var Tassadar = Protoss() //will not print "YOU MUST CONSTRUCT ADDITIONAL PYLONS."

slide-36
SLIDE 36

[Faculty of Science Information and Computing Sciences] 36

Laziness: infjnite list

class List{ let cur: Int init(){ cur = 3} lazy var next: List = List() func sum(cnt: Int) -> Int{ if(cnt == 0){return 0} return self.cur + self.sum(cnt: (cnt-1))} } let Buzz = List() print(Buzz.sum(cnt:140))

slide-37
SLIDE 37

[Faculty of Science Information and Computing Sciences] 37

Swift

Garbage Collection

slide-38
SLIDE 38

[Faculty of Science Information and Computing Sciences] 38

Garbage Collection

Overview

◮ Memory deallocation ◮ Only objects that are passed by reference.

Mark and Sweep

◮ Pauses program ◮ Iterates over memory at least twice ◮ Runtime delay

slide-39
SLIDE 39

[Faculty of Science Information and Computing Sciences] 39

Garbage Collection

Reference Counting

◮ Stores amount of references to each memory chunk ◮ Memory deallocated when counter reaches 0

slide-40
SLIDE 40

[Faculty of Science Information and Computing Sciences] 40

Reference Counting

Example

class Person { let name: String ... } var john = Person(name : "John Appleseed")

Figure 3: Example of a reference to memory

slide-41
SLIDE 41

[Faculty of Science Information and Computing Sciences] 41

Reference Counting

Pros

◮ Garbage is immediately noticed ◮ Operates at runtime ◮ Guarantees memory deallocation

Cons

◮ Reference cycles ◮ Counters in memory (space overhead) ◮ Constant counting (speed overhead) ◮ Multi-node communication

slide-42
SLIDE 42

[Faculty of Science Information and Computing Sciences] 42

Reference Cycle

class Person { let name: String var apartement = Apartement? ... } class Apartement { let unit: String var tenant : Person? } var john = Person(name : "John Appleseed") var unit4A = Apartement(unit : "4A") john.apartement = unit4A unit4A.tenant = john

slide-43
SLIDE 43

[Faculty of Science Information and Computing Sciences] 43

Reference Counting

Reference Cycle

Figure 4: Example of a reference cycle

slide-44
SLIDE 44

[Faculty of Science Information and Computing Sciences] 44

Reference Counting

Preventing Cycles

◮ Additional info ◮ Strong, weak, unowned reference ◮ Link without a hold

slide-45
SLIDE 45

[Faculty of Science Information and Computing Sciences] 45

Reference Counting

Weak Reference

◮ Does not prevent deallocation ◮ Set to nil ◮ Models optional properties ◮ For shorter target lifetime

slide-46
SLIDE 46

[Faculty of Science Information and Computing Sciences] 46

Reference Counting

Weak Reference

class Apartement { weak var tenant : Person? ... }

Figure 5: Example of a weak reference

slide-47
SLIDE 47

[Faculty of Science Information and Computing Sciences] 47

Reference Counting

Unowned Reference

◮ Does not prevent deallocation ◮ Not set to nil! ◮ For larger target lifetime ◮ Models non-optional reference ◮ Must be used safe

slide-48
SLIDE 48

[Faculty of Science Information and Computing Sciences] 48

Reference Counting

Unowned Reference

class Creditcard { unowned let customer : Customer ... }

Figure 6: Example of an unowned reference

slide-49
SLIDE 49

[Faculty of Science Information and Computing Sciences] 49

Swift

Protocols

slide-50
SLIDE 50

[Faculty of Science Information and Computing Sciences] 50

Protocols

A small example protocol FullyNamed { var fullName: String { get } } struct Person: FullyNamed { var fullName: String } let kees = Person(fullName: "Kees Jansen")

slide-51
SLIDE 51

[Faculty of Science Information and Computing Sciences] 51

Protocols

Objects in 2D plane: ◮ Squares ◮ Circle ◮ Etc. We want to know the following: ◮ Posistion ◮ Area ◮ Function: Distance to point In Swift we can use protocols for this!

slide-52
SLIDE 52

[Faculty of Science Information and Computing Sciences] 51

Protocols

Objects in 2D plane: ◮ Squares ◮ Circle ◮ Etc. We want to know the following: ◮ Posistion ◮ Area ◮ Function: Distance to point In Swift we can use protocols for this!

slide-53
SLIDE 53

[Faculty of Science Information and Computing Sciences] 52

Protocols

Defjnition

A protocol is a blueprint for functions and properties. A protocol can be adapted by a: ◮ class ◮ structure ◮ enumeration A type can conform to a protocol. Similar to interfaces in C# or type classes in Haskell.

slide-54
SLIDE 54

[Faculty of Science Information and Computing Sciences] 53

Protocols

Example protocol

protocol Shape { var posistion: Point { get set } var area: Double { get } func distance(point: Point) -> Double static func random() -> Self init(originpoint: Point) }

slide-55
SLIDE 55

[Faculty of Science Information and Computing Sciences] 54

Protocols

Protocol adapted by class

class CircleR5: Shape { var radi = 5.0 var posistion init(originpoint: Point){ self.posistion = originpoint } var area : Double { return Double.pi * radi * radi ...

slide-56
SLIDE 56

[Faculty of Science Information and Computing Sciences] 55

Protocols

Protocol adapted by class

class CircleR5: Shape { ... func distance(point: Point) -> Double{ //Implementation of distance function } static func random() -> CircleR5 { //Implementation of random function } }

slide-57
SLIDE 57

[Faculty of Science Information and Computing Sciences] 56

Protocols

Protocols as a type

Protocols can be used as a full type. For example, we have a random number generator protocol: protocol RandomNumberGenerator { func random() -> Double } And now we can defjne a function that rolls a dice: func rollD6(rng: RandomNumberGenerator) -> Int{ return Int(rng.random() * 6) + 1 }

slide-58
SLIDE 58

[Faculty of Science Information and Computing Sciences] 57

Protocols

Other functionallities

◮ Extend existing types to a protocol extension CircleR5 : FullyNamed{ var fullName: String { return "Circle with radius \(radi)" } }

slide-59
SLIDE 59

[Faculty of Science Information and Computing Sciences] 58

Protocols

Other functionallities

◮ Inheritance protocol InheritingProt: SomeProt, AnotherProt { // protocol definition goes here }

slide-60
SLIDE 60

[Faculty of Science Information and Computing Sciences] 59

Protocols

Other functionallities

◮ Class only protocol ClassOnlyProt: AnyObject, SomeInheritedProt { // class-only protocol definition goes here }

slide-61
SLIDE 61

[Faculty of Science Information and Computing Sciences] 60

Protocols

Other functionallities

◮ Composisition protocol Named { var name: String { get } } protocol Aged { var age: Int { get } } func HappyBirthday(to celebrator: Named & Aged) { print("Happy birthday, \(celebrator.name), you're \(celebrator.age)!") }

slide-62
SLIDE 62

[Faculty of Science Information and Computing Sciences] 61

Protocols

Other functionallities

◮ Check for protocol conformence let objects: [AnyObject] = [ CircleR5(originpoint: (2.0,0,0)), Person(name: "John"), Animal(legs: 4) ] for object in objects { if let objectWithShape = object as? Shape { print("Found a shape!") } else { print("This isn't a shape") } }

slide-63
SLIDE 63

[Faculty of Science Information and Computing Sciences] 62

Protocols

Other functionallities

◮ Extending protocols and default implementations extension RandomNumberGenerator { func randomBool() -> Bool { return random() > 0.5 } }

slide-64
SLIDE 64

[Faculty of Science Information and Computing Sciences] 63

Protocols

Comparison with Haskell Type Classes

◮ No conditional conformance (yet) (Proposal: SE-0143) extension Array: Equatable where Element: Equatable { static func ==(lhs: Array<Element>, rhs: Array<Element>) -> Bool { ... } } ◮ Haskell is not objective oriented ◮ No deriving data Maybe a = Nothing | Just a deriving (Eq, Ord)