Slide 1

Slide 1 text

Swift Dal Rupnik iOS Developer

Slide 2

Slide 2 text

Swift A new programming language for iOS and OS X. Why? The reasons behind Swift development. 1 Grandpa Objective-C was originally developed in early 1980s. Memory The pain of memory management is still present in Objective-C. Safety Dynamic typing of Objective-C is nice, but is it safe? C++ Burden Building on top of C++, has some advantages, but it is also a burden. Syntax Lets face it, the syntax of Objective-C is one of the ugliest on planet.

Slide 3

Slide 3 text

Swift A new programming language for iOS and OS X. Swift is an innovative new programming language for Cocoa and Cocoa Touch. Ready for your next app. “Writing code is interactive and fun, the syntax is concise yet expressive, and apps run lightning-fast.” Swift A new programming language for iOS and OS X. What? The definition itself. 19

Slide 4

Slide 4 text

Swift A new programming language for iOS and OS X. What? Ideas behind Swift. Swift is compiled and works side by side with Objective-C. Just highlighting a couple of features: Playgrounds, Closures, Tuples, Optionals, Extensions, Unwrapping, Type Inference, Generics, Computed Properties, Property Observers, … 3 Safe Compiler can be helpful sometimes. Modern Up-to-date with modern concepts. Powerful Easy to use with powerful features.

Slide 5

Slide 5 text

Swift A new programming language for iOS and OS X. How does Swift syntax compare to other languages? Is it harder or easier to read? Enough. Lets see some nice examples. 4

Slide 6

Slide 6 text

Swift A new programming language for iOS and OS X. Variables Cannot live without them. 6 PHP $x = 0.0; $y = 1.0; $z = 2.0; $welcomeMessage = "Hello world"; Ruby x, y, z = 0.0, 1.0, 2.0 welcomeMessage = "Hello world" Objective-C double x = 0.0, y = 1.0, z = 2.0; NSString* welcomeMessage = @"Hello world"; Swift var x = 0.0, y = 1.0, z = 2.0 let welcomeMessage = "Hello world"

Slide 7

Slide 7 text

Swift A new programming language for iOS and OS X. Operations Basic string operations and operators. 6 PHP $a = "Hello"; $b = "World"; $helloWorld = $a . " " . $b; $helloWorld .= "!"; Ruby a = "Hello" b = "World" helloWorld = a + " " + b helloWorld += "!" Objective-C NSString* a = @"Hello"; NSString* b = @"World"; NSString* helloWorld = [NSString stringWithFormat:@"%@ %@", a, b]; helloWorld = [helloWorld stringByAppendingString:@"!"]; Swift let a = "Hello" let b = "World" let helloWorld = a + " " + b //helloWorld += "!";

Slide 8

Slide 8 text

Swift A new programming language for iOS and OS X. Operations Basic string operations and operators. 6 PHP $a = "Hello"; $b = "World"; $helloWorld = $a . " " . $b; $helloWorld .= "!"; Ruby a = "Hello" b = "World" helloWorld = a + " " + b helloWorld += "!" Objective-C NSString* a = @"Hello"; NSString* b = @"World"; NSString* helloWorld = [NSString stringWithFormat:@"%@ %@", a, b]; helloWorld = [helloWorld stringByAppendingString:@"!"]; Swift let a = "Hello" let b = "World" var helloWorld = a + " " + b helloWorld += "!";

Slide 9

Slide 9 text

Swift A new programming language for iOS and OS X. Loops We do not get far without those. 5 Local variable is 0 Local variable is 1 Local variable is 2 Local variable is 3 Local variable is 4 Local variable is 5 Sample output from a program…

Slide 10

Slide 10 text

Swift A new programming language for iOS and OS X. For loop The basic construct. We all know it. 6 PHP for ($i = 0; $i <= 5; $i++) { echo "Local variable is $i"; } Ruby for i in 0..5 puts "Local variable is #{i}" end Objective-C for (int i = 0; i <= 5; i++){ NSLog(@"Local variable is %d", i); } Swift for i in 0...5 { println ("Local variable is \(i)") }

Slide 11

Slide 11 text

Swift A new programming language for iOS and OS X. Switch Easily control your flow. 6 PHP switch ($i) { case 0: echo "$i equals 0"; break; case 1: echo "$i equals 1"; break; case 2: echo "$i equals 2"; break; } Ruby case i when 0..2 puts "#{i} equals #{i}" else puts "Unknown value" end Objective-C switch (i) { case 0: NSLog(@"%d equals 0", i); break; case 1: NSLog(@"%d equals 1", i); break; case 2: NSLog(@"%d equals 2", i); break; } Swift switch (i) { case 0, 1, 2: println("\(i) equals \(i)"); default: println ("Unknown value"); }

Slide 12

Slide 12 text

Swift A new programming language for iOS and OS X. Functions Main construct of every application. 7 Hello Nina! Hello Miha! Hello Janez! Hello Mateja! Now lets define a function that returns a greeting…

Slide 13

Slide 13 text

Swift A new programming language for iOS and OS X. Functions Basic concept in all languages. 8 PHP function sayHello($personName){ return "Hello, " . $personName . "!"; } Ruby def sayHello(name) var = "Hello, " + name + "!" return var end Objective-C - (NSString *)sayHelloWithPersonName:(NSString *)personName{ return [NSString stringWithFormat:@"Hello, %@!", personName]; } Swift func sayHello(personName: String) -> String { let greeting = "Hello, " + personName + "!" return greeting }

Slide 14

Slide 14 text

Swift A new programming language for iOS and OS X. Functions Basic architecture in all languages. 9 PHP echo sayHello("Nina"); Ruby puts sayHello("Miha") Objective-C NSLog(@"%@", [self sayHello:@"Janez"]); Swift println (sayHello("Mateja"))

Slide 15

Slide 15 text

Swift A new programming language for iOS and OS X. Collections They usually store our data models. 10 PHP $array = array ("Yes", "No", "Maybe"); $hashmap = array ("a" => "Orange", "b" => "Banana", "c" => “Apple"); Ruby array = [ "Yes", "No", "Maybe" ] hashmap = { "a" => "Orange", "b" => "Banana", "c" => "Apple" } Objective-C NSArray *array = @[ @"Yes", @"No", @"Maybe" ]; NSDictionary *hashmap = @{ @"a" : @"Orange", @"b" : @"Banana", @"c" : @"Apple" }; Swift var array = [ "Yes", "No", "Maybe" ] var hashmap = [ "a" : "Orange", "b" : "Banana", "c" : "Apple" ]

Slide 16

Slide 16 text

Swift A new programming language for iOS and OS X. Structures Always copied by value. 10 PHP // Well, can only have a class, so :( class Customer { public $name; public $address; } Ruby # Technically still a class. :( Struct.new("Customer", :name, :address) Objective-C typedef struct Customer { __unsafe_unretained NSString* name; __unsafe_unretained NSString* address; } Customer; Swift struct Customer { var name = "" var address = "" }

Slide 17

Slide 17 text

Swift A new programming language for iOS and OS X. Lets dive into few details of objective- oriented programming on Apple platforms. Fully objective oriented. 4

Slide 18

Slide 18 text

Swift A new programming language for iOS and OS X. Classes The basic construct of Object-Oriented language. 10 PHP // Same as our struct class Customer { public $name; public $address; } Ruby class Customer attr_accessor :name, :address end Objective-C @interface Customer : NSObject @property (nonatomic, copy) NSString* name; @property (nonatomic, copy) NSString* address; @end Swift class Customer { var name = "" var address: String? }

Slide 19

Slide 19 text

Swift A new programming language for iOS and OS X. Initialization Create a new instance of our class. 10 PHP $object = new Customer(); $object->name = "Matej"; Ruby customer = Customer.new() customer.name = "Mateja" Objective-C Customer *customer = [[Customer alloc] init]; customer.name = @"Mojca"; Swift let customer = Customer() customer.name = "Matic"

Slide 20

Slide 20 text

Swift A new programming language for iOS and OS X. Protocols Define an interface for a class. 10 PHP interface Payable { public function pay ($amount); } Ruby ?? Objective-C @protocol Payable - (BOOL)pay:(double)amount; @end Swift protocol Payable { func pay (amount: Double) -> Bool }

Slide 21

Slide 21 text

Swift A new programming language for iOS and OS X. • Encapsulating simple data values • Copying values instead of referencing them • Properties used are also value types Examples: Coordinates, Geometric shapes, … Structures or Classes Which of the two is more appropriate? 10 Structures should be used when:

Slide 22

Slide 22 text

Swift A new programming language for iOS and OS X. Structures or Classes Which of the two is more appropriate? 10 Classes should be used when: • Inheritance is needed • Need more references to a single instance • Using introspection to determine type at runtime Examples: Complex objects, adapters, …

Slide 23

Slide 23 text

Swift A new programming language for iOS and OS X. Advanced features We already know and understand the basics. So yes, we get it. Show us more interesting stuff. Every programming languages has it’s own specific functionalities and approaches that it uses to solve most common language problems. Lets take a look at a few in Swift. 11

Slide 24

Slide 24 text

Swift A new programming language for iOS and OS X. Optionals A method can return a nil object. 12 Objective-C NSDictionary *numberOfLegs = @{ @"ant" : @6, @"snake" : @0, @"cheetah" : @4 }; if (!numberOfLegs[@"leopard"]){ NSLog(@"Leopard was not found."); } Swift let numberOfLegs = ["ant": 6, "snake": 0, "cheetah": 4] let possibleLegCount: Int? = numberOfLegs["leopard"] if possibleLegCount == nil { println("Leopard was not found") }

Slide 25

Slide 25 text

Swift A new programming language for iOS and OS X. Unwrapping Retrieve the value of the optional. 12 Forced unwrapping var aNumber : Int? if aNumber != nil { println ("Number: \(aNumber!)") } println ("Number: \(aNumber!)") // Runtime error Optional chaining class Person { var residence: Residence? } class Residence { var numberOfRooms = 1 } let aPerson = Person() if let roomCount = aPerson.residence?.numberOfRooms { println("Residence has \(roomCount) room(s).") }

Slide 26

Slide 26 text

Swift A new programming language for iOS and OS X. Tuples Return multiple values from methods. 13 Objective-C // Basically we cannot, so we return a hashmap :) 
 - (NSDictionary *)refreshWebPage{ return @{ @"statusCode" : @200, @"message" : @"success" }; } Swift func refreshWebPage() -> (code: Int, message: String) { return (200, "Success") } let (statusCode, message) = refreshWebPage()

Slide 27

Slide 27 text

Swift A new programming language for iOS and OS X. Closures For some, also known as blocks. 14 Objective-C // Thanks to fuckingblocksyntax.com 
 int (^sum)(int a, int b) = ^int(int a, int b){ return a * b; } int result = sum(5, 5); Swift // Reminds of anything? let sum: (a: Int, b: Int) -> (Int) = { return a * b } let result = sum (5, 5)

Slide 28

Slide 28 text

Swift A new programming language for iOS and OS X. Enumerations Common type for a group of related values. 14 Objective-C typedef NS_ENUM(NSUInteger, CompassPoint) { CompassPointNorth, CompassPointEast, CompassPointWest, CompassPointSouth, }; CompassPoint currentDirection = CompassPointNorth; currentDirection = CompassPointWest; Swift enum CompassPoint { case North, East, West, South } var currentDirection = CompassPoint.North currentDirection = .West

Slide 29

Slide 29 text

Swift A new programming language for iOS and OS X. Generics Reusable code for multiple types. 14 Objective-C // Could use C++ templates, but we already have dynamic // typing. NSArray *array = @[ ... ]; Swift func swapTwoValues(inout a: T, inout b: T) { let temporaryA = a a = b b = temporaryA }

Slide 30

Slide 30 text

Swift A new programming language for iOS and OS X. Extensions Ability to add methods to existing classes without derivation. 15 Objective-C (header file) @interface NSString (Additional) - (NSString *)shortString; @end Objective-C (implementation file) @implementation NSString (Additional) - (NSString *)shortString{ return @"Short"; } @end Swift extension String { func short () -> String { return "Short" } }

Slide 31

Slide 31 text

Swift A new programming language for iOS and OS X. Lazy instantiation Delay creation of an object until first time needed. 14 Objective-C @property (nonatomic, strong) NSMutableArray *items; - (NSMutableArray *)items { if (!_items) { _items = [NSMutableArray array]; } return _items; } [self.items addObject:@"An item"]; Swift lazy var items = [String]() items.append ("An item")

Slide 32

Slide 32 text

Swift A new programming language for iOS and OS X. Type casting Checking type of object at runtime. 14 Objective-C NSInteger strings = 0; NSArray *array = @[ @"a", @4, @"b", @"c", @12, @19 ]; for (id object in array) { if ([object isKindOfClass:[NSString class]]) { strings++; } } Swift var strings = 0 let array = ["a", 4, "b", "c", 12, 19] for object in array { if object is String { strings++ } }

Slide 33

Slide 33 text

Swift A new programming language for iOS and OS X. Type casting Checking type of object at runtime. 14 Objective-C NSArray *array = @[ @"aa", @4, @"bbb", @"c", @12, @19 ]; for (id object in array) { if ([object isKindOfClass:[NSString class]]) { NSString* str = object; NSLog(@"Length: %d", str.length); } } Swift let array = ["aa", 4, "bbb", "c", 12, 19] for object in array { if let str = object as? String { let length = countElements(str) println("Length: \(length)"); } }

Slide 34

Slide 34 text

Swift A new programming language for iOS and OS X. Some details Just a sneak peek of how it works. Swift was built to support Objective-C out of the box. But for certain API’s, some modifications are required, to make them fully supported. But what about Objective-C?
 I have apps in it!

Slide 35

Slide 35 text

Swift A new programming language for iOS and OS X. Interoperability Use Swift and Objective-C in the same project. 15 Annotations @objc(MYThing) class Thing { @objc(initWithName:) init(name: String) { ... } } // Objective-C [[MYThing alloc] initWithName:nil]; AnyObject in Swift let defaults = NSUserDefaults.standardUserDefaults() let lastRefreshDate: AnyObject? = userDefaults.objectForKey(“LastRefreshDate") if let date = lastRefreshDate as? NSDate { println("\(date.timeIntervalSinceReferenceDate)") } Objective-C used id, Swift uses AnyObject. If object does not inherit from NSObject, add the annotation.

Slide 36

Slide 36 text

Swift A new programming language for iOS and OS X. Memory management Swift uses reference counting. 15 Weak references var reference1: Person? = Person() // Ref. count: 1 weak var reference2: Person? = reference1 // Ref. count: 1 reference1 = nil // Ref. count: 0 - Deallocated Automatic reference counting var reference1: Person? = Person() // Ref. count: 1 var reference2: Person? = reference1 // Ref. count: 2 reference1 = nil // Ref. count: 1 reference2 = nil // Ref. count: 2 - Deallocated All pointers are strong by default. Weak references are not counted and must be optional.

Slide 37

Slide 37 text

16 Playgrounds! Lets just try it out now!

Slide 38

Slide 38 text

Swift A new programming language for iOS and OS X. Swift 1.2 Latest version, released in February 2015. 15 Improved Optional Binding if let a = a { if let b = b { if b != 0 { println("(a / b) = \(a / b)") } } } // New if let a = a, b = b where b != 0 { println("(a / b) = \(a / b)") } Nullability annotations in Objective-C @property (nonnull, nonatomic, readonly) NSArray *locations; @property (nullable, nonatomic, readonly) Location *latestLocation; // In Swift var locations: [AnyObject] { get } var latestLocation: Location? { get } Headers will now become much larger. If any condition is false, execution is stopped.

Slide 39

Slide 39 text

Swift A new programming language for iOS and OS X. Summary Is it production ready? 17  Apple Only Right now, it only works on Apple systems, but there are many projects to bring Swift compiler to other platforms! Production 
 Ready Patterns and API’s are not final yet, but can still be used to deploy applications! No reasons to wait for anything. Libraries Many libraries from it’s grandpa are still missing, but the community is increasing every day!

Slide 40

Slide 40 text

Swift A new programming language for iOS and OS X. The End Finally came to the end of our story. 18 Do you have any questions? Twitter: @thelegoless GitHub: legoless