Save 37% off PRO during our Black Friday Sale! »

Swift

F52a1009516f2cdf6e120ae96079e633?s=47 Dal Rupnik
February 28, 2015

 Swift

Presentation on Apple's new programming language called Swift held at Mobile Monday in February 2015.

F52a1009516f2cdf6e120ae96079e633?s=128

Dal Rupnik

February 28, 2015
Tweet

Transcript

  1. Swift Dal Rupnik iOS Developer

  2. 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.
  3. 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
  4. 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.
  5. 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
  6. 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"
  7. 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 += "!";
  8. 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 += "!";
  9. 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…
  10. 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)") }
  11. 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"); }
  12. 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…
  13. 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 }
  14. 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"))
  15. 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" ]
  16. 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 = "" }
  17. 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
  18. 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? }
  19. 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"
  20. 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 <NSObject> - (BOOL)pay:(double)amount; @end Swift protocol Payable { func pay (amount: Double) -> Bool }
  21. 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:
  22. 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, …
  23. 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
  24. 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") }
  25. 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).") }
  26. 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()
  27. 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)
  28. 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
  29. 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<T>(inout a: T, inout b: T) { let temporaryA = a a = b b = temporaryA }
  30. 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" } }
  31. 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")
  32. 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++ } }
  33. 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)"); } }
  34. 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!
  35. 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.
  36. 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.
  37. 16 Playgrounds! Lets just try it out now!

  38. 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.
  39. 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!
  40. 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