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.
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
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.
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"
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…
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)") }
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 = "" }
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? }
• 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:
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, …
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
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") }
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).") }
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)
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
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 }
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++ } }
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)"); } }
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!
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.
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.
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!