swift: apple's new programming language for ios and os x

Post on 22-Apr-2015

317 Views

Category:

Technology

3 Downloads

Preview:

Click to see full reader

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

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

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

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?!

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

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];}

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"];

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"]);

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

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

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

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)}

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)")}

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

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)")

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")}

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}

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)

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 }

Join the conversation on Twitter: @SoftArchConf #SA2014

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

DEMOSwift REPL

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) }}

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 { /* ... */ } } }}

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 } }}

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)")}

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)

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) }}

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)}

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

Join the conversation on Twitter: @SoftArchConf #SA2014

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

Swift and Objective-C

Join the conversation on Twitter: @SoftArchConf #SA2014

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

DEMOBuilding an iOS app with Swift

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

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

top related