Swift: Apple's New Programming Language for iOS and OS X

31
Join the conversation on Twitter: @SoftArchConf #SA2014 This presentation: http://s.sashag.net/sa-swift Swift Apple’s New Programming Language Sasha Goldshtein CTO, Sela Group blog.sashag.net @goldshtn

description

Presentation from Software Architect 2014, covering Swift -- Apple's new programming language for iOS and OS X. The presentation focuses on Swift's language features, which make it so different from mainstream programming languages. Towards the end of the live talk, we also built an iOS app using Swift.

Transcript of Swift: Apple's New Programming Language for iOS and OS X

Page 1: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

SwiftApple’s New Programming Language

Sasha GoldshteinCTO, Sela Group

blog.sashag.net @goldshtn

Page 2: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Apple WWDC Announcements

• iOS 8 and OS X Yosemite

• Xcode 6

• Swift

Page 3: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Minus Bazillion Points

“Every feature starts out in the hole by 100 points, which means that it has to have a significant net positive effect on the overall package for it to make it into the language.”

– Eric Gunnerson, C# compiler team

If a language feature starts at -100 points, where does a new language start?!

Page 4: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Objective-C Popularity

• Objective-C owes all its popularity to the meteoric rise of the iPhone

App Store introduced

Page 5: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

What’s Wrong with Objective-CExhibit One

// Ignore the horrible syntax for a second.// But here's the charmer:// 1) if 'str' is null, we return NSNotFound (232-1)// 2) if 'arr' is null, we return 0

+ (NSUInteger)indexOfString:(NSString *)str inArray:(NSArray *)arr{ return [arr indexOfObject:str];}

Page 6: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

What’s Wrong with Objective-CExhibit Two

// This compiles and crashes at runtime with:// "-[__NSArrayI addObject:]: unrecognized selector// sent to instance 0x7a3141c0"

NSMutableArray *array = [NSArray array];[array addObject:@"hello"];

Page 7: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

What’s Wrong with Objective-CExhibit Three

NSMutableArray *array = [NSMutableArray array];[array addObject:@"hello"];[array addObject:@17]; // This compiles just fineNSString *string = array[1]; // Yes, the "17"// This works and prints 17NSLog(@"%@", string);// But this crashesNSLog(@"%@", [string stringByAppendingString:@"hmm"]);

Page 8: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Swift Language Principles

• Clean and modern

• Type-safe and generic

• Extensible

• Functional

• Productive

• Compiled to native

• Seamlessly interops with Objective-C

Page 9: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Why Not an Existing Language?

• Good philosophical question

• If you want some more philosophy:http://s.sashag.net/why-swift

We will now review some of the interesting language decisions, which make Swift different from mainstream languages

Page 10: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Variables and Constants

let size = 42let name = "Dave"

var address = "14 Franklin Way"address = "16 Calgary Drive"

var city: Stringcity = "London"

var pi: Double = 3.14

Page 11: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Strings and Arrays

var fullAddress = city + " " + addressprintln("\(name)'s at \(city.capitalizedString)")

var customers = ["Dave", "Kate", "Jack"]var addresses = [String]()addresses += fullAddress

if customers[2].hasPrefix("Ja") { customers.removeAtIndex(2)}

Page 12: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Dictionaries

var orderSummary = [ "Dave": 11000, "Kate": 14000, "Jack": 13500]orderSummary["Kate"] = 17500

for (customer, orders) in orderSummary { println("\(customer) -> \(orders)")}

Page 13: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Null

“I call it my billion-dollar mistake. It was the invention of the null reference in 1965. […] I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.”

– Sir Charles Antony Richard Hoare, 2009

Page 14: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Optional Types

var myName: StringmyName = nil // Does not compile!

var jeffsOrders: Int?jeffsOrders = orderSummary["Jeff”]if jeffsOrders { let orders: Int = jeffsOrders!}

var customerName: String? = getCustomer()println("name: \(customerName?.uppercaseString)")

Page 15: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Pattern Matching

switch milesFlown["Jeff"]! {case 0..<25000: println("Jeff is a Premier member")case 25000..<50000: println("Jeff is a Silver member")case 50000..<75000: println("Jeff is a Gold member")case 75000..<100000: println("Jeff is a Platinum member")default: println("Jeff is an Elite member")}

Page 16: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Pattern Matching

switch reservation.fareClass {case "F", "A", "J", "C": milesBonus = 2.5 // business/firstcase "Y", "B": milesBonus = 2.0 // full-fare economycase "M", "H": milesBonus = 1.5 // top-tier discount economycase let fc where fc.hasPrefix("Z"): milesBonus = 0 // upgrades don't earn milesdefault: milesBonus = 1.0}

Page 17: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Functions and Tuples

func square(x: Int) -> Int { return x * x }

func powers(x: Int) -> (Int, Int, Int) { return (x, x*x, x*x*x)}

// The first tuple element is ignoredlet (_, square, cube) = powers(42)

Page 18: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Closures

func countIf(arr: [Int], pred: (Int) -> Bool) { var count = 0 for n in arr { if pred(n) { ++count } } return count}countIf([1, 2, 3, 4], { n in n % 2 == 0 })

var squares = [17, 3, 11, 5, 7].map({ x in x * x })sort(&squares, { a, b in a > b })sort(&squares) { a, b in a > b }sort(&squares) { $0 > $1 }

Page 19: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

DEMOSwift REPL

Page 20: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Classes

class FrequentFlier { let name: String var miles: Double = 0 init(name: String) { self.name = name } func addMileage(fareClass: String, dist: Int) { miles += bonus(fareClass) * Double(dist) }}

Page 21: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Custom Properties and Observers

class MileageStatus { var miles: Double = 0.0 { willSet { assert(newValue >= miles) // can't decrease one's mileage } }

var status: String { get { switch miles { /* ... */ } } }}

Page 22: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Smart Enums

enum MemberLevel { case Silver case Gold case Platinum func milesRequired() -> Int { switch self { case .Silver: return 25000 case .Gold: return 50000 case .Platinum: return 75000 } }}

Page 23: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Stateful Enums

enum HttpResponse { case Success(body: String) case Error(description: String, statusCode: Int)}switch fakeHttpRequest("example.org") {case let .Error(desc, status) where status >= 500: println("internal server error: \(desc)")case let .Error(desc, status): println("error \(status) = \(desc)")case .Success(let body): println("success, body = \(body)")}

Page 24: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Extensions

extension Int { var absoluteValue: Int { get { return abs(self) } } func times(action: () -> Void) { for _ in 1...self { action() } }}5.times { println("hello") }println((-5).absoluteValue)

Page 25: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Generics

class Queue<T> { var items = [T]() var depth: Int { get { return items.count } } func enqueue(item: T) { items.append(item) } func dequeue() -> T { return items.removeAtIndex(0) }}

Page 26: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Operators

struct Complex { var r: Double, i: Double func add(z: Complex) -> Complex { return Complex(r: r+z.r, i: i+z.i) } }

@infix func +(z1: Complex, z2: Complex) -> Complex { return z1.add(z2)}

Page 27: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Custom Operators (Oh My!)

operator prefix &*^%!~ {}@prefix func &*^%!~(s: String) -> String { return s.uppercaseString}

operator infix ^^ { associativity left }@infix func ^^(a: Double, b: Double) -> Double { return pow(a, b)}

println(&*^%!~"hello") // prints "HELLO"println(2.0^^4.0) // prints 8.0

Page 28: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Swift and Objective-C

Page 29: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

DEMOBuilding an iOS app with Swift

Page 30: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Wrapping Up

• Most iOS developers are extremely excited about Swift

• Swift has a much smoother learning curve and fixes many Objective-C mistakes

• For the foreseeable future though, we will still use both languages

Page 31: Swift: Apple's New Programming Language for iOS and OS X

Join the conversation on Twitter: @SoftArchConf #SA2014

This presentation: http://s.sashag.net/sa-swift

Thank You!

Sasha Goldshtein

blog.sashag.net

@goldshtn

s.sashag.net/sa-swift