[Faculty of Science Information and Computing Sciences] 1
Concepts of programming languages Swift Lukas, Anvar, Roald, Bart, - - PowerPoint PPT Presentation
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
[Faculty of Science Information and Computing Sciences] 2
Birth of a new language
Swift… isn’t it beautiful?
◮ Developed in secret
[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
[Faculty of Science Information and Computing Sciences] 4
Objective C
◮ Introduced by NeXT
Figure 1: Steve Jobs
[Faculty of Science Information and Computing Sciences] 5
Objective C
◮ Introduced by NeXT
Figure 2: Steve Jobs
[Faculty of Science Information and Computing Sciences] 6
Objective C
◮ Introduced by NeXT ◮ Widely used after fjrst iPhone
[Faculty of Science Information and Computing Sciences] 7
Objective C
◮ Introduced by NeXT ◮ Widely used after fjrst iPhone ◮ Steep learning curve
[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";
[Faculty of Science Information and Computing Sciences] 9
Swift
Apple came to the rescue and developed Swift!
◮ Inferred typing
[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
[Faculty of Science Information and Computing Sciences] 11
Swift - Inferred typing
Though Swift allows inferred typing it is still static typed
[Faculty of Science Information and Computing Sciences] 12
Swift
Apple came to the rescue and developed Swift!
◮ Inferred typing ◮ Neat Closures
[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 }
[Faculty of Science Information and Computing Sciences] 14
Swift
Apple came to the rescue and developed Swift!
◮ Inferred typing ◮ Neat Closures ◮ Protocols
[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
[Faculty of Science Information and Computing Sciences] 16
Swift
Apple came to the rescue and developed Swift!
◮ Inferred typing ◮ Neat Closures ◮ Protocols ◮ Generics
[Faculty of Science Information and Computing Sciences] 17
Swift
Get length of generic type func <T: count>length(_ variable: T) -> Int { return variable.count }
[Faculty of Science Information and Computing Sciences] 18
Swift
Comparison with OO languages
[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!" }
[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 }
[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" }; }
[Faculty of Science Information and Computing Sciences] 22
Multiple Return Values
// Swift func getPerson() -> (firstName: String, lastName: String) { return ("Steve", "Jobs") }
[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; }
[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);
[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)
[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); }
[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) }
[Faculty of Science Information and Computing Sciences] 28
Swift
Optionals
[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
[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")
[Faculty of Science Information and Computing Sciences] 31
Optionals
So why are they awesome?
[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") }
[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?
[Faculty of Science Information and Computing Sciences] 34
Laziness
◮ Not standard in Swift ◮ keyword lazy ◮ more cumbersome to do than in Haskell
[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."
[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))
[Faculty of Science Information and Computing Sciences] 37
Swift
Garbage Collection
[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
[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
[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
[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
[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
[Faculty of Science Information and Computing Sciences] 43
Reference Counting
Reference Cycle
Figure 4: Example of a reference cycle
[Faculty of Science Information and Computing Sciences] 44
Reference Counting
Preventing Cycles
◮ Additional info ◮ Strong, weak, unowned reference ◮ Link without a hold
[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
[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
[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
[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
[Faculty of Science Information and Computing Sciences] 49
Swift
Protocols
[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")
[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!
[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!
[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.
[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) }
[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 ...
[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 } }
[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 }
[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)" } }
[Faculty of Science Information and Computing Sciences] 58
Protocols
Other functionallities
◮ Inheritance protocol InheritingProt: SomeProt, AnotherProt { // protocol definition goes here }
[Faculty of Science Information and Computing Sciences] 59
Protocols
Other functionallities
◮ Class only protocol ClassOnlyProt: AnyObject, SomeInheritedProt { // class-only protocol definition goes here }
[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)!") }
[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") } }
[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 } }
[Faculty of Science Information and Computing Sciences] 63