185
© 2015 Apple Inc. All rights reserved. Redistribution or public display not permitted without written permission from Apple. What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106

What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

  • Upload
    others

  • View
    8

  • Download
    0

Embed Size (px)

Citation preview

Page 1: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

© 2015 Apple Inc. All rights reserved. Redistribution or public display not permitted without written permission from Apple.

What’s New in Swift

Chris Lattner Sr. Director, Developer ToolsJohn McCall Compiler Engineer

Featured #WWDC15

Session 106

Page 2: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Goals

Page 3: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Goals

Refine language and tools fundamentals

Page 4: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Goals

Refine language and tools fundamentalsAffordances for writing robust and safe code

Page 5: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Goals

Refine language and tools fundamentalsAffordances for writing robust and safe codeEnable expressive libraries and APIs

Page 6: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

What’s New

Swift 2

Page 7: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

What’s New

FundamentalsPattern MatchingAvailability CheckingProtocol ExtensionsError Handling

Swift 2

Page 8: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Fundamentals

Page 9: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

enum Animals { case Dog, Cat, Troll, Dragon }

Enums

let a = Animals.Dragon

Page 10: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

enum Animals { case Dog, Cat, Troll, Dragon }

Enums

let a = Animals.Dragon

print(a)

(Enum Value)

Page 11: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

enum Animals { case Dog, Cat, Troll, Dragon }

Enums

let a = Animals.Dragon

print(a)

Animals.Dragon

Page 12: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Associated Values in Enums

Page 13: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

enum Either<T1, T2> { case First(T1) case Second(T2) }

Associated Values in Enums

Page 14: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

enum Either<T1, T2> { case First(T1) case Second(T2) }

Associated Values in Enums

Playground Console Output

Playground execution failed: /var/folders/3w/j_3ky_8966j30xj_2b9v6b0h0000gq/T/./lldb/2582/playground1.swift:28:6: error: unimplemented ir generation feature non-fixed multi-payload enum layout enum Either<T1, T2> { ^

Page 15: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

enum Either<T1, T2> { case First(T1) case Second(T2) }

Associated Values in Enums

Page 16: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

enum Tree<T> {   case Leaf(T)   }

case Node(Tree, Tree)

Recursive Enums

Page 17: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

enum Tree<T> {   case Leaf(T)   }

case Node(Tree, Tree)

Recursive Enums

Recursive value type 'Tree<T>' is not allowed!

Page 18: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

enum Tree<T> {   case Leaf(T)   }

case Node(Tree, Tree)

Recursive Enums

indirect

Page 19: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

“do” Statement

let a = Animals.Troll ...

Page 20: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

“do” Statement

let a = Animals.Troll ...

do {

}

Page 21: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

“do” Statement

let a = Animals.Troll ...

do { // // // // // lots of code here // //

do {

}

Page 22: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

“do” Statement

let a = Animals.Troll ...

do { // // // // // lots of code here // //

do {

}

repeat {

Page 23: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Option Sets

Page 24: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Option Sets

viewAnimationOptions = .Repeat | .CurveEaseIn | .TransitionCurlUpSwift 1:

Page 25: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Option Sets

viewAnimationOptions = .Repeat | .CurveEaseIn | .TransitionCurlUp

viewAnimationOptions = nil

if viewAnimationOptions & .TransitionCurlUp != nil {

Swift 1:

Page 26: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Option Sets

viewAnimationOptions = .Repeat | .CurveEaseIn | .TransitionCurlUp

viewAnimationOptions = nil

if viewAnimationOptions & .TransitionCurlUp != nil {

viewAnimationOptions = [.Repeat, .CurveEaseIn, .TransitionCurlUp]

Swift 2:

Swift 1:

Page 27: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Option Sets

viewAnimationOptions = .Repeat | .CurveEaseIn | .TransitionCurlUp

viewAnimationOptions = nil

if viewAnimationOptions & .TransitionCurlUp != nil {

viewAnimationOptions = []

viewAnimationOptions = [.Repeat, .CurveEaseIn, .TransitionCurlUp]

Swift 2:

Swift 1:

Page 28: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Option Sets

viewAnimationOptions = .Repeat | .CurveEaseIn | .TransitionCurlUp

viewAnimationOptions = nil

if viewAnimationOptions & .TransitionCurlUp != nil {

viewAnimationOptions = []

viewAnimationOptions = [.Repeat, .CurveEaseIn, .TransitionCurlUp]

if viewAnimationOptions.contains(.TransitionCurlUp) {

Swift 2:

Swift 1:

Page 29: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Defining an Option Set

struct MyFontStyle : OptionSetType {

Page 30: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Defining an Option Set

struct MyFontStyle : OptionSetType {let rawValue : Int

Page 31: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Defining an Option Set

struct MyFontStyle : OptionSetType {let rawValue : Int

static let Bold = MyFontStyle(rawValue: 1) static let Italic = MyFontStyle(rawValue: 2) static let Underline = MyFontStyle(rawValue: 4) static let Strikethrough = MyFontStyle(rawValue: 8) }

Page 32: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Defining an Option Set

struct MyFontStyle : OptionSetType {

myFont.style = [] myFont.style = [.Underline] myFont.style = [.Bold, .Italic]

if myFont.style.contains(.StrikeThrough) {

let rawValue : Int static let Bold = MyFontStyle(rawValue: 1) static let Italic = MyFontStyle(rawValue: 2) static let Underline = MyFontStyle(rawValue: 4) static let Strikethrough = MyFontStyle(rawValue: 8) }

Protocol-Oriented Programming in Swift Nob Hill Wednesday 2:30PM

Page 33: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Functions and Methods

func save(name: String, encrypt: Bool) { … }

class Widget { func save(name: String, encrypt: Bool) { … }

Page 34: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Functions and Methods

func save(name: String, encrypt: Bool) { … }

widget.save("thing", encrypt: false)

save("thing", false)

class Widget { func save(name: String, encrypt: Bool) { … }

Page 35: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Functions and Methods

func save(name: String, encrypt: Bool) { … }

widget.save("thing", encrypt: false)

save("thing", false)

Swift 1 followed Objective-C:• No label for global functions• Labels for second argument (and later) in methods

class Widget { func save(name: String, encrypt: Bool) { … }

Page 36: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

save("thing",

func save(name: String, encrypt: Bool) { … }

widget.save("thing", encrypt: false)

class Widget { func save(name: String, encrypt: Bool) { … }

false)

Consistent Argument Labels

Page 37: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

save("thing",

func save(name: String, encrypt: Bool) { … }

widget.save("thing", encrypt: false)

class Widget { func save(name: String, encrypt: Bool) { … }

encrypt: false)

Consistent Argument Labels

Page 38: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

All ‘func’ declarations are uniform:• First argument is implied by the base function name• Labels are used for subsequent arguments

save("thing",

func save(name: String, encrypt: Bool) { … }

widget.save("thing", encrypt: false)

class Widget { func save(name: String, encrypt: Bool) { … }

encrypt: false)

Consistent Argument Labels

Page 39: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

All ‘func’ declarations are uniform:• First argument is implied by the base function name• Labels are used for subsequent arguments

save("thing",

func save(name: String, encrypt: Bool) { … }

widget.save("thing", encrypt: false)

class Widget { func save(name: String, encrypt: Bool) { … }

encrypt: false)

No change to imported C and Objective-C APIs

Consistent Argument Labels

Page 40: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

save("foo", encrypt: true)func save(name: String, encrypt: Bool)

Argument Label Controls

Page 41: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

save("foo", encrypt: true)func save( name: String, encrypt: Bool)_

Argument Label Controls

Page 42: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

save("foo", encrypt: true)func save( name: String, encrypt : Bool)_ encrypt

Argument Label Controls

Page 43: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

save("foo", encrypt: true)

save(name: "foo", encrypt: true)

Duplicate first name to enable argument label

func save(

func save(name name: String, encrypt: Bool)

name: String, encrypt : Bool)_ encrypt

Argument Label Controls

Page 44: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

save("foo", encrypt: true)

save(name: "foo", encrypt: true)

Duplicate first name to enable argument label

Underscore disables argument labels

func save(

save("foo", true)func save(name : String, _ encrypt : Bool)

func save(name name: String, encrypt: Bool)

name: String, encrypt : Bool)_ encrypt

Argument Label Controls

Page 45: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

save("foo", encrypt: true)

save(name: "foo", encrypt: true)

Duplicate first name to enable argument label

Underscore disables argument labels

func save(

save("foo", true)func save(name : String, _ encrypt : Bool)

func save(name name: String, encrypt: Bool)

name: String, encrypt : Bool)_ encrypt

Argument Label Controls

Much simpler model:• Consistency between functions and methods• No special rules for defaulted parameters• # argument syntax has been removed

Page 46: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Diagnostics

Page 47: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

struct MyCoordinates { var points : [CGPoint]

points[42].x = 19

} }

func updatePoint() {

Diagnostics

Page 48: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

struct MyCoordinates { var points : [CGPoint]

points[42].x = 19

} }

func updatePoint() {

Diagnostics

^'@lvalue $T7' is not identical to 'CGFloat'!

Page 49: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

struct MyCoordinates { var points : [CGPoint]

points[42].x = 19

} }

func updatePoint() {

Diagnostics

^Cannot assign to the result of this expression!

Page 50: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

struct MyCoordinates { var points : [CGPoint]

points[42].x = 19

} }

func updatePoint() {

Diagnostics

^Cannot assign to ‘x’: ‘self’ is immutable!

Page 51: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

struct MyCoordinates { var points : [CGPoint]

points[42].x = 19

} }

func updatePoint() {

Diagnostics

^

mutating

Fix-it Mark method ‘mutating’ to make ‘self’ mutableCannot assign to ‘x’: ‘self’ is immutable

Cannot assign to ‘x’: ‘self’ is immutable!

Page 52: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

New Warnings

func processEntries() { var entries = ...

let size = entries.count

var indices = entries.map { $0.index } indices.sort()

Page 53: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

New Warnings

func processEntries() { var entries = ...

let size = entries.count

var indices = entries.map { $0.index } indices.sort()

Variable ‘entries’ was never mutated

Page 54: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

New Warnings

func processEntries() { var entries = ...

let size = entries.count

var indices = entries.map { $0.index } indices.sort()

Variable ‘entries’ was never mutated

Immutable value ‘size’ was never used

Page 55: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

New Warnings

func processEntries() { var entries = ...

let size = entries.count

var indices = entries.map { $0.index } indices.sort()

Variable ‘entries’ was never mutated

Immutable value ‘size’ was never used

‘sort’ result is unused; use ‘sortInPlace’ to mutate in-place

Page 56: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

SDK Improvements

class func requestHeaderFieldsWithCookies(cookies: [AnyObject] ) -> [NSObject : AnyObject]

!!

Page 57: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

SDK Improvements

class func requestHeaderFieldsWithCookies(cookies: [AnyObject] ) -> [NSObject : AnyObject]

Page 58: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

SDK Improvements

class func requestHeaderFieldsWithCookies(cookies: [AnyObject] ) -> [NSObject : AnyObject]

[NSHTTPCookie])[String : String]

Adoption of new features and best practices:• Nullability qualifiers• Objective-C typed collections• NS_ENUM, NS_OPTIONS, instancetype, @property, etc

Swift and Objective-C Interoperability Mission Tuesday 1:30PM

What’s New in Cocoa Presidio Tuesday 1:30PM

Page 59: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Unit Testing

Page 60: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Unit Testing and Access Control

Page 61: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Unit Testing

Your code is now built in a “compile for testing” build mode:• Unit tests use

• public and internal symbols are now available

@testable import MyApp

and Access Control

Page 62: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Unit Testing

What’s New in Xcode Presidio Tuesday 9:00AM

UI Testing in Xcode Nob Hill Wednesday 11:00AM

No behavior change for release builds:• Same optimizations • Same insurance against symbol collisions

Your code is now built in a “compile for testing” build mode:• Unit tests use

• public and internal symbols are now available

@testable import MyApp

and Access Control

Page 63: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Rich Comments

Page 64: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Rich Comments

Page 65: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Rich Comments

Authoring Rich Playgrounds Presidio Wednesday 10:00AM

Page 66: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language
Page 67: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language
Page 68: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language
Page 69: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language
Page 70: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

So Much More…

Page 71: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Default implementations in protocolsC function pointers + closuresRecursive nested functionsif/do labeled breaksSIMD VectorsMirrors APIreadLine()@nonobjc

So Much More…

Page 72: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Default implementations in protocolsC function pointers + closuresRecursive nested functionsif/do labeled breaksSIMD VectorsMirrors APIreadLine()@nonobjc

The Swift Programming LanguageXcode 7 release notes

So Much More…

Page 73: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Pattern Matching

Page 74: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

“if let” Statement

...

{

   } }

func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {    if let dest = segue.destinationViewController as? BlogViewController

Page 75: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

“if let” Statement: the “Pyramid of Doom”

    if {    if {                  

                }    }

let blogIndex = tableView.indexPathForSelectedRow()?.rowsegue.identifier == blogSegueIdentifierdest.blogName = swiftBlogs[blogIndex] ... ...

{

   } }

func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {    if let dest = segue.destinationViewController as? BlogViewController

Page 76: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

“if let” Statement: the “Pyramid of Doom”

    if {    if {                  

                }    }

let blogIndex = tableView.indexPathForSelectedRow()?.rowsegue.identifier == blogSegueIdentifierdest.blogName = swiftBlogs[blogIndex] ... ...

{

   } }

func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {    if let dest = segue.destinationViewController as? BlogViewController

Page 77: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

“if let” Statement: Compound Conditions

    where {let blogIndex = tableView.indexPathForSelectedRow()?.row

segue.identifier == blogSegueIdentifierdest.blogName = swiftBlogs[blogIndex] ... ...

   } }

func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {    if let dest = segue.destinationViewController as? BlogViewController

Page 78: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

“if let” Statement: Compound Conditions

    where {let blogIndex = tableView.indexPathForSelectedRow()?.row

segue.identifier == blogSegueIdentifierdest.blogName = swiftBlogs[blogIndex] ... ...

   } }

func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {    if let dest = segue.destinationViewController as? BlogViewController

Page 79: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Patterns for Early Exits

func process(json: AnyObject) -> Either<Person,String> { let name: String = json["name"] as? String if name == nil { return .Second(”missing name”)

?

}

Page 80: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Patterns for Early Exits

?

func process(json: AnyObject) -> Either<Person,String> { let name: String = json["name"] as? String if name == nil { return .Second(”missing name”)

?

}

let year: Int = json["year"] as? Int if year == nil { return .Second("missing year”)

}

Page 81: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Patterns for Early Exits

let person = processPerson(name , year ) return .First(person)

! !

?

func process(json: AnyObject) -> Either<Person,String> { let name: String = json["name"] as? String if name == nil { return .Second(”missing name”)

?

}

}

let year: Int = json["year"] as? Int if year == nil { return .Second("missing year”)

}

Page 82: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Patterns for Early Exits

let person = processPerson(name , year ) return .First(person)

! !

?

func process(json: AnyObject) -> Either<Person,String> { let name: String = json["name"] as? String if name == nil { return .Second(”missing name”)

?

}

}

let year: Int = json["year"] as? Int if year == nil { return .Second("missing year”)

}

Page 83: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Patterns for Early Exits

let person = processPerson(name , year ) return .First(person)

!

!

func process(json: AnyObject) -> Either<Person,String> { let name: String = json["name"] as? String if name == nil { return .Second(”missing name”)

}

}

let year: Int = json["year"] as? Int if year == nil { return .Second("missing year”)

}

Page 84: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

“guard” Statement

guard let name = json["name"] as? String else { return .Second("missing name") }

Page 85: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

else { return .Second("missing name") } guard return .Second("missing year")

“guard” Statement

let year = json["year"] as? Int else

func process(json: AnyObject) -> Either<Person,String> { guard let name = json["name"] as? String

let person = processPerson(name, year) return .First(person)

}

}

{

Page 86: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

“guard” Statement: Compound Conditions

, return .Second(“bad input”)

let year = json["year"] as? Int else

}

}

let person = processPerson(name, year) return .First(person)

{

func process(json: AnyObject) -> Either<Person,String> { guard let name = json["name"] as? String

Page 87: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Pattern Matching with Switch

switch bar() {case .MyEnumCase(let value): where value != 42:

Page 88: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Pattern Matching with Switch

switch bar() {case .MyEnumCase(let value): where value != 42: doThing(value)

default: break }

Page 89: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Pattern Matching with “if case”

switch bar() {case .MyEnumCase(let value): where value != 42: doThing(value)

default: break }

Page 90: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Pattern Matching with “if case”

if case .MyEnumCase(let value) = bar() where value != 42 { doThing(value) }

switch bar() {case .MyEnumCase(let value): where value != 42: doThing(value)

default: break }

Page 91: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

“for … in” Filtering

for value in mySequence {

Page 92: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

“for … in” Filtering

for value in mySequence { if value != "" { doThing(value) } }

Page 93: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

“for … in” Filtering

for value in mySequence { if value != "" { doThing(value) } }

for value in mySequence where value != "" { doThing(value) }

Page 94: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

“for … in” Filtering

for value in mySequence { if value != "" { doThing(value) } }

for value in mySequence where value != "" { doThing(value) }

for case .MyEnumCase(let value) in enumValues { doThing(value) }

Page 95: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Pattern Matching Summary

Page 96: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Pattern Matching Summary

New “guard” statement for early exits

Page 97: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Pattern Matching Summary

New “guard” statement for early exits

‘case’ uniformly supported in control flow statements- switch/case, if case, guard case, for-in case, while case

Page 98: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Pattern Matching Summary

New “guard” statement for early exits

‘case’ uniformly supported in control flow statements- switch/case, if case, guard case, for-in case, while case

Other improvements- x? pattern for optionals- Improved exhaustiveness checker- “Unreachable case” warning

Page 99: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

API Availability Checking

John McCall Type Checker

Page 100: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

New APIs

extension NSButton { @available(OSX 10.10.3) var springLoaded: Bool }

Page 101: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

The Old Approach

@IBOutlet var dropButton: NSButton!

override func awakeFromNib() { dropButton.springLoaded = true }

Page 102: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

The Old Approach

@IBOutlet var dropButton: NSButton!

override func awakeFromNib() { dropButton.springLoaded = true }

-[NSButton setSpringLoaded:]: unrecognized selector sent to instance 0x100010AD0!

Page 103: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

extension NSButton { @available(OSX 10.10.3) var springLoaded: Bool }

The Old Approach

Page 104: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

extension NSButton { @available(OSX 10.10.3) var springLoaded: Bool }

The Old Approach

Page 105: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

The Old Approach

}

dropButton.springLoaded = true

@IBOutlet var dropButton: NSButton!

override func awakeFromNib() {

Page 106: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

The Old Approach

dropButton.springLoaded = true

@IBOutlet var dropButton: NSButton!

override func awakeFromNib() {") {

} }

if respondsToSelector("setSpringLoaded dropButton.

Page 107: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

The Old Approach

dropButton.springLoaded = true

@IBOutlet var dropButton: NSButton!

override func awakeFromNib() {") {

} }

if respondsToSelector("setSpringLoaded dropButton.

Page 108: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

:

The Old Approach

dropButton.springLoaded = true

@IBOutlet var dropButton: NSButton!

") {

} }

if respondsToSelector("setSpringLoaded dropButton.

override func awakeFromNib() {

Page 109: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

:

The Old Approach

dropButton.springLoaded = true

@IBOutlet var dropButton: NSButton!

") {

} }

if respondsToSelector("setSpringLoaded dropButton.

override func awakeFromNib() {

Page 110: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

The Better Approach

}

@IBOutlet var dropButton: NSButton!

override func awakeFromNib() { dropButton.springLoaded = true

Page 111: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

The Better Approach

}

@IBOutlet var dropButton: NSButton!

override func awakeFromNib() { dropButton.springLoaded = true error: springLoaded is only available

on Mac OS X 10.10.3 or later!

Page 112: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

The Better Approach

if #available(OSX 10.10.3, *) {

} }

@IBOutlet var dropButton: NSButton!

override func awakeFromNib() {

dropButton.springLoaded = true

Page 113: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

The Better Approach

if #available(OSX 10.10.3, *) {

} }

@IBOutlet var dropButton: NSButton!

override func awakeFromNib() {

dropButton.springLoaded = true

Page 114: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Availability Checking

Take advantage of new capabilities without abandoning usersEasy, expressive checksStatically enforced by the language

Swift in Practice Presidio Thursday 2:30PM

Page 115: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Protocol Extensions

Page 116: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Extensions

extension Array { func countIf(match: Element -> Bool) -> Int {

}

var n = 0 for value in self { if match(value) { n++ } } return n }

func countIf<T : CollectionType>(collection: T, match: T.Generator.Element -> Bool) -> Int {

Page 117: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Extensions

extension Array { func countIf(match: Element -> Bool) -> Int {

}

var n = 0 for value in self { if match(value) { n++ } } return n }

func countIf<T : CollectionType>(collection: T, match: T.Generator.Element -> Bool) -> Int {

Page 118: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

func countIf<T : CollectionType>(collection: T, match: T.Generator.Element -> Bool) -> Int {

Extensions vs. Global Functions

var n = 0 for value in self { if match(value) { n++ } } return n }

extension Array { func countIf(match: Element -> Bool) -> Int {

{

Page 119: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

var n = 0 for value in self { if match(value) { n++ } } return n }

Extensions

extension Array func countIf(match: Element -> Bool) -> Int {

}

{

Page 120: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

extension Array func countIf(match: Element -> Bool) -> Int {

Protocol Extensions

var n = 0 for value in self { if match(value) { n++ } } return n }

}

{

Page 121: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

extension Array func countIf(match: Element -> Bool) -> Int {

Protocol Extensions

var n = 0 for value in self { if match(value) { n++ } } return n }

}

{CollectionType

Page 122: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Methodification

let x = filter(map(numbers) { $0 * 3 }) { $0 >= 0 }

Global generic algorithms are becoming methods

Swift 1:

Page 123: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Methodification

let x = numbers.map { $0 * 3 }.filter { $0 >= 0 }

let x = filter(map(numbers) { $0 * 3 }) { $0 >= 0 }

Global generic algorithms are becoming methods

Swift 1:

Swift 2:

Page 124: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

More consistent use of methods in the standard library

Powerful new design patterns

Protocol Extensions

Protocol-Oriented Programming in Swift Nob Hill Wednesday 2:30PM

Page 125: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Error Handling

Page 126: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Errors, Errors Everywhere

A big opportunity to improve programming in Swift• Safety• Readability• Expressiveness

Page 127: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Errors, Errors Everywhere

Common problem, but the standard solutions aren't good, in different ways• Too easy to ignore errors• Repetitive, bug-prone patterns• Hard to reason about implicit behavior

Page 128: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Kinds of Error

?Trivial errors• Int(someString) can fail, but an optional return type is fine

Page 129: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Kinds of Error

! ?Trivial errors

• Int(someString)

Logic errors• Assertions, overflows, NSException, etc.

Page 130: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Kinds of Error

!

?Detailed, recoverable errors• File not found• Network failure• User cancellation

Trivial errors• Int(someString)

Logic errors• Assertions, overflows, NSException, etc.

Page 131: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Error Handling

func preflight( url.checkResourceIsReachable() resetState() }

) {

Page 132: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Error Handling

func preflight( url.checkResourceIsReachable() resetState() }

) {

Page 133: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Error Handling with NSError

func preflight(inout error: NSError? -> Bool if url.checkResourceIsReachableAndReturnError(&error) { return false } resetState() return true }

) {

Page 134: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Error Handling with NSError

func preflight(inout error: NSError? -> Bool if url.checkResourceIsReachableAndReturnError(&error) { return false } resetState() return true }

) {

Page 135: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Downsides

Adds a lot of boilerplateOriginal code is hiding in there somewhere

func preflight(inout error: NSError?) -> Bool { if url.checkResourceIsReachableAndReturnError(&error) { return false } resetState() return true }

Page 136: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

func preflight(inout error: NSError?) -> Bool { if url.checkResourceIsReachableAndReturnError(&error) { return false } resetState() return true }

Adds a lot of boilerplateOriginal code is hiding in there somewhereManually implementing conventions without help

Downsides

Page 137: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

func preflight(inout error: NSError?) -> Bool { if return false } resetState() return true }

Adds a lot of boilerplateOriginal code is hiding in there somewhereManually implementing conventions without help

url.checkResourceIsReachableAndReturnError(&error) {

Downsides

Page 138: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

func preflight(inout error: NSError?) -> Bool { if return false } resetState() return true }

Adds a lot of boilerplateOriginal code is hiding in there somewhereManually implementing conventions without help

url.checkResourceIsReachableAndReturnError(&error) {!

Downsides

Page 139: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Upsides

Obvious that checkResourceIsReachable can fail

func preflight(inout error: NSError?) -> Bool { if !url.checkResourceIsReachableAndReturnError(&error) { return false } resetState() return true }

Page 140: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Obvious that checkResourceIsReachable can failObvious that preflight can fail

Upsides

func preflight(inout error: NSError?) -> Bool { if !url.checkResourceIsReachableAndReturnError(&error) { return false } resetState() return true }

Page 141: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Obvious that checkResourceIsReachable can failObvious that preflight can fail

Upsides

func preflight(inout error: NSError?) -> Bool { if !url.checkResourceIsReachableAndReturnError(&error) { return false } resetState() return true }

Page 142: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Obvious that checkResourceIsReachable can failObvious that preflight can failAll the control flow is explicit

Upsides

func preflight(inout error: NSError?) -> Bool { if !url.checkResourceIsReachableAndReturnError(&error) { return false } resetState() return true }

Page 143: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

resetState()

Error Handling in Swift

func preflight() { url.checkResourceIsReachable()

}

Page 144: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

resetState()

Error Handling in Swift

func preflight() { url.checkResourceIsReachable()

}

error: call can throw, but it is not marked with 'try' and the error is not handled!

Page 145: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

resetState()

try

func preflight() { url.checkResourceIsReachable()

}

try

Page 146: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

resetState()

try

func preflight() { url.checkResourceIsReachable()

}

tryerror: call can throw, but the error is not handled!

Page 147: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

func preflight()

resetState() }

try url.checkResourceIsReachable()

Propagating Errors

throws {

Page 148: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

-> Bool { do { try url.checkResourceIsReachable() resetState() return true } catch { return false

Handling Errors

func preflight()

} }

Page 149: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

-> Bool { do { try url.checkResourceIsReachable() resetState() return true } catch let error { return false

Patterns with “catch”

func preflight()

} }

Page 150: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

-> Bool { do { try url.checkResourceIsReachable() resetState() return true } catch NSURLError.FileDoesNotExist { return true } catch let error { return false

Patterns with “catch”

func preflight()

} }

Page 151: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

do { try resetState() } catch { fatalError("I sure didn't expect this error: \(error)") }

func preflight() {

url.checkResourceIsReachable()

}

Aside: Impossible Errors

Page 152: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

try! resetState()

func preflight() {url.checkResourceIsReachable()

}

Aside: Impossible Errors

Page 153: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Error Types

ErrorType is a protocol in the Swift standard library

Any type that conforms to ErrorType can be thrown and caught• NSError already conforms to ErrorType• Can make your own types conform as well

Page 154: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Enums as Error Types

enum is great for groups of related errors• Can carry data in a payload• Compiler handles protocol conformance details automatically

Page 155: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Defining Your Own Error Type

enum DataError : ErrorType { case MissingName case MissingYear // add more later }

Page 156: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Defining Your Own Error Type

func processPerson(json: AnyObject) -> Either<Person,String> { guard let name = json["name"] as? String { return .Second("missing name") }

guard let year = json["year"] as? Int { return .Second("missing year") }

return .First(Person(name, year)) }

Page 157: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

func processPerson(json: AnyObject) -> Either<Person,String> { guard let name = json["name"] as? String { throw DataError.MissingName }

guard let year = json["year"] as? Int { throw DataError.MissingYear }

return .First(Person(name, year)) }

Defining Your Own Error Type

Page 158: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Defining Your Own Error Type

func processPerson(json: AnyObject) throws -> Person { guard let name = json["name"] as? String { throw DataError.MissingName }

guard let year = json["year"] as? Int { throw DataError.MissingYear }

return Person(name, year) }

Page 159: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Cleaning Up

func processSale(json: AnyObject) throws { guard let buyerJSON = json["buyer"] as? NSDictionary { throw DataError.MissingBuyer } let buyer = try processPerson(buyerJSON)

guard let price = json["price"] as? Int { throw DataError.MissingPrice }

return Sale(buyer, price) }

Page 160: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

func processSale(json: AnyObject) throws { guard let buyerJSON = json["buyer"] as? NSDictionary { throw DataError.MissingBuyer } let buyer = try processPerson(buyerJSON)

guard let price = json["price"] as? Int { throw DataError.MissingPrice }

return Sale(buyer, price) }

Notifying at the Start

Page 161: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

func processSale(json: AnyObject) throws { delegate?.didBeginReadingSale() guard let buyerJSON = json["buyer"] as? NSDictionary { throw DataError.MissingBuyer } let buyer = try processPerson(buyerJSON)

guard let price = json["price"] as? Int { throw DataError.MissingPrice }

return Sale(buyer, price) }

Notifying at the Start

Page 162: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

return Sale(buyer, price) }

Notifying at the End

func processSale(json: AnyObject) throws { delegate?.didBeginReadingSale() guard let buyerJSON = json["buyer"] as? NSDictionary { throw DataError.MissingBuyer } let buyer = try processPerson(buyerJSON)

guard let price = json["price"] as? Int { throw DataError.MissingPrice }

Page 163: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

return Sale(buyer, price) }

delegate?.didEndReadingSale()

Notifying at the End

func processSale(json: AnyObject) throws { delegate?.didBeginReadingSale() guard let buyerJSON = json["buyer"] as? NSDictionary { throw DataError.MissingBuyer } let buyer = try processPerson(buyerJSON)

guard let price = json["price"] as? Int { throw DataError.MissingPrice }

Page 164: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Notifying at the End

func processSale(json: AnyObject) throws { delegate?.didBeginReadingSale() guard let buyerJSON = json["buyer"] as? NSDictionary { throw DataError.MissingBuyer } let buyer = try processPerson(buyerJSON)

guard let price = json["price"] as? Int { throw DataError.MissingPrice } return Sale(buyer, price) }

delegate?.didEndReadingSale()

Page 165: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Redundancy

throw DataError.MissingBuyer } let buyer = try processPerson(buyerJSON)

guard let price = json["price"] as? Int {

func processSale(json: AnyObject) throws { delegate?.didBeginReadingSale() guard let buyerJSON = json["buyer"] as? NSDictionary { throw DataError.MissingBuyer } let buyer = try processPerson(buyerJSON)

guard let price = json["price"] as? Int { throw DataError.MissingPrice } delegate?.didEndReadingSale() return Sale(buyer, price) }

Page 166: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Redundancy

func processSale(json: AnyObject) throws { delegate?.didBeginReadingSale() guard let buyerJSON = json["buyer"] as? NSDictionary {

throw DataError.MissingBuyer } let buyer = try processPerson(buyerJSON)

guard let price = json["price"] as? Int {

throw DataError.MissingPrice }

delegate?.didEndReadingSale() return Sale(buyer, price) }

Page 167: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Redundancy

delegate?.didEndReadingSale()

delegate?.didEndReadingSale()

func processSale(json: AnyObject) throws { delegate?.didBeginReadingSale() guard let buyerJSON = json["buyer"] as? NSDictionary {

throw DataError.MissingBuyer } let buyer = try processPerson(buyerJSON)

guard let price = json["price"] as? Int {

throw DataError.MissingPrice }

delegate?.didEndReadingSale() return Sale(buyer, price) }

Page 168: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Redundancy and Awkwardness

func processSale(json: AnyObject) throws { delegate?.didBeginReadingSale() guard let buyerJSON = json["buyer"] as? NSDictionary { delegate?.didEndReadingSale() throw DataError.MissingBuyer } let buyer

guard let price = json["price"] as? Int { delegate?.didEndReadingSale() throw DataError.MissingPrice }

delegate?.didEndReadingSale() return Sale(buyer, price) }

Page 169: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Redundancy and Awkwardness

func processSale(json: AnyObject) throws { delegate?.didBeginReadingSale() guard let buyerJSON = json["buyer"] as? NSDictionary { delegate?.didEndReadingSale() throw DataError.MissingBuyer } let buyer : Person do { buyer = try processPerson(buyerJSON) } catch { delegate?.didEndReadingSale() throw error } guard let price = json["price"] as? Int { delegate?.didEndReadingSale() throw DataError.MissingPrice

Page 170: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

func processSale(json: AnyObject) throws { delegate?.didBeginReadingSale()

throw DataError.MissingBuyer } let buyer

Defer Actions

guard let buyerJSON = json["buyer"] as? NSDictionary {

guard let price = json["price"] as? Int {

throw DataError.MissingPrice }

Page 171: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

func processSale(json: AnyObject) throws { delegate?.didBeginReadingSale()

throw DataError.MissingBuyer } let buyer

defer { delegate?.didEndReadingSale() }

= try processPerson(buyerJSON)

return Sale(buyer, price) }

Defer Actions

guard let buyerJSON = json["buyer"] as? NSDictionary {

guard let price = json["price"] as? Int { throw DataError.MissingPrice }

Page 172: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

A Quick Note About Implementation

Page 173: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

A Quick Note About Implementation

"Exception handling" schemes• Anything can throw• Performance heavily biased against exceptions

Page 174: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

A Quick Note About Implementation

"Exception handling" schemes• Anything can throw• Performance heavily biased against exceptions

Swift error handling is more balanced• Not table-based unwinding• Similar in performance to an explicit “if” statement

Page 175: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Swift 1: extension NSIncrementalStore { func loadMetadata(error: NSErrorPointer) -> Bool }

Works Great with Cocoa

Page 176: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Swift 1: extension NSIncrementalStore { func loadMetadata(error: NSErrorPointer) -> Bool }

Swift 2: extension NSIncrementalStore { func loadMetadata() throws }

Works Great with Cocoa

Page 177: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Swift 1: extension NSData { class func bookmarkDataWithContentsOfURL(bookmarkFileURL: NSURL,                                     error: NSErrorPointer) -> NSData? }

Works Great with Cocoa

Page 178: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Swift 1: extension NSData { class func bookmarkDataWithContentsOfURL(bookmarkFileURL: NSURL,                                     error: NSErrorPointer) -> NSData? }

Swift 2: extension NSData { class func bookmarkDataWithContentsOfURL(bookmarkFileURL: NSURL) throws -> NSData }

Works Great with Cocoa

Page 179: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Error Handling

Expressive way to handle errorsSafe, reliable programming modelReadable and maintainable

Page 180: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Swift 2

What’s New in Swift 2

Page 181: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

FundamentalsPattern MatchingAvailability CheckingProtocol ExtensionsError Handling

Swift 2

What’s New in Swift 2

Page 182: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

More Information

Swift Language Documentationhttp://developer.apple.com/swift

Apple Developer Forumshttp://developer.apple.com/forums

Stefan LesserSwift [email protected]

Page 183: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Related Sessions

Swift and Objective-C Interoperability Mission Tuesday 1:30PM

Improving Your Existing Apps with Swift Pacific Heights Tuesday 3:30PM

Authoring Rich Playgrounds Presidio Wednesday 10:00AM

Protocol-Oriented Programming in Swift Nob Hill Wednesday 2:30PM

Optimizing Swift Performance Presidio Thursday 9:00AM

Swift in Practice Presidio Thursday 2:30PM

Building Better Apps with Value Types in Swift Mission Friday 2:30PM

Page 184: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language

Labs

Swift Lab Developer Tools Lab A Tuesday 1:30PM

Swift Lab Developer Tools Lab A Wednesday 9:00AM

Swift Lab Developer Tools Lab A Wednesday 1:30PM

Swift Lab Developer Tools Lab A Thursday 9:00AM

Swift Lab Developer Tools Lab A Thursday 1:30PM

Swift Lab Developer Tools Lab A Friday 9:00AM

Swift Lab Developer Tools Lab A Friday 1:30PM

Page 185: What’s New in Swift · What’s New in Swift Chris Lattner Sr. Director, Developer Tools John McCall Compiler Engineer Featured #WWDC15 Session 106. Goals. Goals Refine language