intermediate swift language by apple

396
© 2014 Apple Inc. All rights reserved. Redistribution or public display not permitted without written permission from Apple. #WWDC14 Intermediate Swift Session 403 Brian Lanier Joe Groff Developer Publications Engineer Swift Compiler Engineer Tools

Upload: jamesfeng2

Post on 27-Aug-2014

475 views

Category:

Software


1 download

DESCRIPTION

Intermediate Swift Language by Apple

TRANSCRIPT

Page 1: Intermediate Swift Language by Apple

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

#WWDC14

Intermediate Swift

Session 403 Brian Lanier Joe Groff Developer Publications Engineer Swift Compiler Engineer

Tools

Page 2: Intermediate Swift Language by Apple

What You Will Learn

Page 3: Intermediate Swift Language by Apple

What You Will Learn

Optionals

Page 4: Intermediate Swift Language by Apple

What You Will Learn

Optionals

Memory management

Page 5: Intermediate Swift Language by Apple

What You Will Learn

Optionals

Memory management

Initialization

Page 6: Intermediate Swift Language by Apple

What You Will Learn

Optionals

Memory management

Initialization

Closures

Page 7: Intermediate Swift Language by Apple

What You Will Learn

Optionals

Memory management

Initialization

Closures

Pattern matching

Page 8: Intermediate Swift Language by Apple

Optionals

Brian Lanier Developer Publications Engineer

Page 9: Intermediate Swift Language by Apple

String to Integer

> Enter your age: > !

!

!

_

Page 10: Intermediate Swift Language by Apple

String to Integer

> Enter your age: > !

!

!

_

let age = response.toInt()

Page 11: Intermediate Swift Language by Apple

String to Integer

> Enter your age: > !

let age = response.toInt()

!

Page 12: Intermediate Swift Language by Apple

String to Integer

> Enter your age: > !

let age = response.toInt()

!

34

Page 13: Intermediate Swift Language by Apple

String to Integer

> Enter your age: > !

let age = response.toInt()

!

Page 14: Intermediate Swift Language by Apple

String to Integer

> Enter your age: > !

let age = response.toInt()

!

thirty

Page 15: Intermediate Swift Language by Apple

String to Integer

> Enter your age: > !

let age = response.toInt()

!

Page 16: Intermediate Swift Language by Apple

String to Integer

> Enter your age: > !

let age = response.toInt()

!

wouldn't you like to know

Page 17: Intermediate Swift Language by Apple

> Enter your age: > !

let age = response.toInt()

String to Integer

Page 18: Intermediate Swift Language by Apple

> Enter your age: > !

let age = response.toInt()

String to Integer

how rude!

Page 19: Intermediate Swift Language by Apple

> Enter your age: > !

let age = response.toInt()

String to Integer

-1NSNotFound

NULL

nil 0

INT_MAX

NSIntegerMax

Nil

how rude!

Page 20: Intermediate Swift Language by Apple

> Enter your age: > !

let age = response.toInt()

String to Integer

-1NSNotFound

NULL

nil 0

INT_MAX

NSIntegerMax

Nil?

how rude!

Page 21: Intermediate Swift Language by Apple

Optional Type

Page 22: Intermediate Swift Language by Apple

Optional Type

Represents possibly missing values !

!

!

!

!

Page 23: Intermediate Swift Language by Apple

Optional Type

Represents possibly missing values !

var optionalNumber: Int? // default initialized to nil !

!

! 6

Page 24: Intermediate Swift Language by Apple

Optional Type

Represents possibly missing values !

var optionalNumber: Int? // default initialized to nil !

!

! 6

Page 25: Intermediate Swift Language by Apple

Optional Type

Represents possibly missing values !

var optionalNumber: Int? // default initialized to nil !

optionalNumber = 6 !

! 6

Page 26: Intermediate Swift Language by Apple

Optional Type

Represents possibly missing values !

var optionalNumber: Int? // default initialized to nil !

optionalNumber = 6 !

! 6

Page 27: Intermediate Swift Language by Apple

One Sentinel to Rule Them All

> Enter your age: > thirty !

let age = response.toInt() // age: Int? = nil

Page 28: Intermediate Swift Language by Apple

Non-Optional Types

!

!

var myString: String = "Look, a real string!" !

!

var myObject: MyClass = MyClass()

Page 29: Intermediate Swift Language by Apple

Non-Optional Types

Non-optional types can't be nil

!

var myString: String = nil // compile-time error !

var myObject: MyClass = nil // compile-time error

Page 30: Intermediate Swift Language by Apple

Optional Return Types

func findIndexOfString(string: String, array: String[]) -> Int !

!

!

!

!

}

{

Page 31: Intermediate Swift Language by Apple

Optional Return Types

func findIndexOfString(string: String, array: String[]) -> Int !

!

!

!

!

}

? {

Page 32: Intermediate Swift Language by Apple

Optional Return Types

func findIndexOfString(string: String, array: String[]) -> Int? { for (index, value) in enumerate(array) { !

!

} }

Page 33: Intermediate Swift Language by Apple

Optional Return Types

func findIndexOfString(string: String, array: String[]) -> Int? { for (index, value) in enumerate(array) { if value == string { return index } } }

Page 34: Intermediate Swift Language by Apple

Optional Return Types

func findIndexOfString(string: String, array: String[]) -> Int? { for (index, value) in enumerate(array) { if value == string { return index } } return nil }

Page 35: Intermediate Swift Language by Apple

Unwrapping Optionals

var neighbors = ["Alex", "Anna", "Madison", "Dave"] let index = findIndexOfString("Madison", neighbors) !

Page 36: Intermediate Swift Language by Apple

var neighbors = ["Alex", "Anna", "Madison", "Dave"] let index = findIndexOfString("Madison", neighbors) !

if index { println("Hello, \(neighbors[index])") } else { println("Must've moved away") }

Unwrapping Optionals

Page 37: Intermediate Swift Language by Apple

var neighbors = ["Alex", "Anna", "Madison", "Dave"] let index: Int? = findIndexOfString("Madison", neighbors) !

if index { println("Hello, \(neighbors[index])") } else { println("Must've moved away") } // error: value of optional type 'Int?' not unwrapped

Unwrapping Optionals

Page 38: Intermediate Swift Language by Apple

var neighbors = ["Alex", "Anna", "Madison", "Dave"] let index = findIndexOfString("Madison", neighbors) !

if index { println("Hello, \(neighbors[index!])") } else { println("Must've moved away") }

Forced Unwrapping

Page 39: Intermediate Swift Language by Apple

var neighbors = ["Alex", "Anna", "Madison", "Dave"] let index = findIndexOfString("Madison", neighbors) !

if index { println("Hello, \(neighbors[index!])") } else { println("Must've moved away") }

Forced Unwrapping

Hello, Madison

Page 40: Intermediate Swift Language by Apple

var neighbors = ["Alex", "Anna", "Madison", "Dave"] let index = findIndexOfString("Reagan", neighbors) !

!

println("Hello, \(neighbors[index!])") // runtime error!

Forced Unwrapping

Page 41: Intermediate Swift Language by Apple

Test and unwrap at the same time

!

var neighbors = ["Alex", "Anna", "Madison", "Dave"] let index = findIndexOfString("Anna", neighbors) !

Optional Binding

Page 42: Intermediate Swift Language by Apple

Test and unwrap at the same time

!

var neighbors = ["Alex", "Anna", "Madison", "Dave"] let index = findIndexOfString("Anna", neighbors) !

if let indexValue = index { println("Hello, \(neighbors[indexValue])") } else { println("Must've moved away") }

Optional Binding

Page 43: Intermediate Swift Language by Apple

Test and unwrap at the same time

!

var neighbors = ["Alex", "Anna", "Madison", "Dave"] let index = findIndexOfString("Anna", neighbors) !

if let indexValue = index { // index is of type Int? println("Hello, \(neighbors[indexValue])") } else { println("Must've moved away") }

Optional Binding

Page 44: Intermediate Swift Language by Apple

Test and unwrap at the same time

!

var neighbors = ["Alex", "Anna", "Madison", "Dave"] let index = findIndexOfString("Anna", neighbors) !

if let indexValue = index { // indexValue is of type Int println("Hello, \(neighbors[indexValue])") } else { println("Must've moved away") }

Optional Binding

Page 45: Intermediate Swift Language by Apple

Test and unwrap at the same time

!

var neighbors = ["Alex", "Anna", "Madison", "Dave"] let index = findIndexOfString("Anna", neighbors) !

if let indexValue = index { // indexValue is of type Int println("Hello, \(neighbors[indexValue])") } else { println("Must've moved away") }

Optional Binding

Page 46: Intermediate Swift Language by Apple

Test and unwrap at the same time

!

var neighbors = ["Alex", "Anna", "Madison", "Dave"] !

!

if let index = findIndexOfString("Anna", neighbors) { println("Hello, \(neighbors[index])") // index is of type Int } else { println("Must've moved away") }

Optional Binding

Page 47: Intermediate Swift Language by Apple

Test and unwrap at the same time

!

var neighbors = ["Alex", "Anna", "Madison", "Dave"] !

!

if let index = findIndexOfString("Anna", neighbors) { println("Hello, \(neighbors[index])") // index is of type Int } else { println("Must've moved away") }

Optional Binding

Hello, Anna

Page 48: Intermediate Swift Language by Apple

Optional Binding

class Person { var residence: Residence? } !

Page 49: Intermediate Swift Language by Apple

Optional Binding

class Person { var residence: Residence? } !

class Residence { var address: Address? } !

Page 50: Intermediate Swift Language by Apple

Optional Binding

class Person { var residence: Residence? } !

class Residence { var address: Address? } !

class Address { var buildingNumber: String? var streetName: String? var apartmentNumber: String? }

Page 51: Intermediate Swift Language by Apple

Optional Binding

let paul = Person()

Person

residence: nil

Page 52: Intermediate Swift Language by Apple

Optional Binding

let paul = Person()

Person

residence:

Residence

address: nil

Page 53: Intermediate Swift Language by Apple

Optional Binding

let paul = Person()

Person

residence:

Residence

address:

Address

buildingNumber: nil

streetName: nil

apartmentNumber: nil

Page 54: Intermediate Swift Language by Apple

Optional Binding

let paul = Person()

Person

residence:

Residence

address:

Address

buildingNumber: "243"

streetName: "Main St."

apartmentNumber: nil

Page 55: Intermediate Swift Language by Apple

Optional Binding

var addressNumber: Int? !

if let home = paul.residence { !

!

!

!

!

!

}

Page 56: Intermediate Swift Language by Apple

Optional Binding

var addressNumber: Int? !

if let home = paul.residence { if let postalAddress = home.address { !

!

!

!

} }

Page 57: Intermediate Swift Language by Apple

Optional Binding

var addressNumber: Int? !

if let home = paul.residence { if let postalAddress = home.address { if let building = postalAddress.buildingNumber { !

!

} } }

Page 58: Intermediate Swift Language by Apple

Optional Binding

var addressNumber: Int? !

if let home = paul.residence { if let postalAddress = home.address { if let building = postalAddress.buildingNumber { if let convertedNumber = building.toInt() { } } } }

Page 59: Intermediate Swift Language by Apple

Optional Binding

var addressNumber: Int? !

if let home = paul.residence { if let postalAddress = home.address { if let building = postalAddress.buildingNumber { if let convertedNumber = building.toInt() { addressNumber = convertedNumber } } } }

Page 60: Intermediate Swift Language by Apple

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

Optional Chaining

Page 61: Intermediate Swift Language by Apple

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

Optional Chaining

?

nil

Int

Page 62: Intermediate Swift Language by Apple

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

Optional Chaining

? Int

nil

Page 63: Intermediate Swift Language by Apple

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

Optional Chaining

? Int

nil

Page 64: Intermediate Swift Language by Apple

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

Optional Chaining

?

nil

Int

Page 65: Intermediate Swift Language by Apple

Optional Chaining

?

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

nil

Int

Page 66: Intermediate Swift Language by Apple

Optional Chaining

?

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

nil

Int

Page 67: Intermediate Swift Language by Apple

Optional Chaining

?

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

nil

Int

Page 68: Intermediate Swift Language by Apple

Optional Chaining

?

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

nil

Int

Page 69: Intermediate Swift Language by Apple

Optional Chaining

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

?

nil

Int

Page 70: Intermediate Swift Language by Apple

Optional Chaining

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

?

nil

Int

Page 71: Intermediate Swift Language by Apple

Optional Chaining

?

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

nil

Int

Page 72: Intermediate Swift Language by Apple

Optional Chaining

?

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

nil

Int

Page 73: Intermediate Swift Language by Apple

Optional Chaining

?

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

nil

Int

Page 74: Intermediate Swift Language by Apple

Optional Chaining

?

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

nil

Int

Page 75: Intermediate Swift Language by Apple

Optional Chaining

?

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

nil

Int

Page 76: Intermediate Swift Language by Apple

Optional Chaining

?

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

nil

Int

Page 77: Intermediate Swift Language by Apple

Optional Chaining

?

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

nil

Int

Page 78: Intermediate Swift Language by Apple

Optional Chaining

?

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

nil

Int

Page 79: Intermediate Swift Language by Apple

Optional Chaining

?

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

"243"

nil

Int

Page 80: Intermediate Swift Language by Apple

Optional Chaining

?

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

243

nil

Int

Page 81: Intermediate Swift Language by Apple

Int

Optional Chaining

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

nil

?

Page 82: Intermediate Swift Language by Apple

Int

Optional Chaining

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

nil

?

Page 83: Intermediate Swift Language by Apple

Optional Chaining

243

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

Page 84: Intermediate Swift Language by Apple

Optional Chaining

Combine with optional binding to unwrap !

Page 85: Intermediate Swift Language by Apple

Optional Chaining

Combine with optional binding to unwrap !

if let addressNumber = paul.residence?.address?.buildingNumber?.toInt() { addToDatabase("Paul", addressNumber) }

Page 86: Intermediate Swift Language by Apple

enum Optional<T> { case None case Some(T) }

Optionals Under the Hood

• Advanced Swift Presidio Thursday 11:30PM

Page 87: Intermediate Swift Language by Apple

Optionals

Page 88: Intermediate Swift Language by Apple

Optionals

Use optionals to safely work with possibly missing values • Missing values are nil

• Present values are wrapped in an optional

Page 89: Intermediate Swift Language by Apple

Optionals

Use optionals to safely work with possibly missing values • Missing values are nil

• Present values are wrapped in an optional

Unwrap an optional to access its underlying value • Use the forced-unwrapping operator (!) only if you are sure

• Use if let optional binding to test and unwrap at the same time

Page 90: Intermediate Swift Language by Apple

Optionals

Use optionals to safely work with possibly missing values • Missing values are nil

• Present values are wrapped in an optional

Unwrap an optional to access its underlying value • Use the forced-unwrapping operator (!) only if you are sure

• Use if let optional binding to test and unwrap at the same time

Optional chaining (?) is a concise way to work with chained optionals

Page 91: Intermediate Swift Language by Apple

Memory Management

Joe Groff Swift Compiler Engineer

Page 92: Intermediate Swift Language by Apple

Automatic Reference Counting

Page 93: Intermediate Swift Language by Apple

Automatic Reference Counting

class BowlingPin {}

func juggle(count: Int) { var left = BowlingPin()

Page 94: Intermediate Swift Language by Apple

Automatic Reference Counting

class BowlingPin {}

func juggle(count: Int) { var left = BowlingPin()

BowlingPin

Page 95: Intermediate Swift Language by Apple

Automatic Reference Counting

class BowlingPin {}

func juggle(count: Int) { var left = BowlingPin()

BowlingPin

left

Page 96: Intermediate Swift Language by Apple

Automatic Reference Counting

class BowlingPin {}

func juggle(count: Int) { var left = BowlingPin() if count > 1 { var right = BowlingPin()

BowlingPin

left

BowlingPin

right

Page 97: Intermediate Swift Language by Apple

Automatic Reference Counting

class BowlingPin {}

func juggle(count: Int) { var left = BowlingPin() if count > 1 { var right = BowlingPin() right = left BowlingPin

left right

Page 98: Intermediate Swift Language by Apple

Automatic Reference Counting

class BowlingPin {}

func juggle(count: Int) { var left = BowlingPin() if count > 1 { var right = BowlingPin() right = left } // right goes out of scope

BowlingPin

left

Page 99: Intermediate Swift Language by Apple

Automatic Reference Counting

class BowlingPin {}

func juggle(count: Int) { var left = BowlingPin() if count > 1 { var right = BowlingPin() right = left } // right goes out of scope

BowlingPin

left

Page 100: Intermediate Swift Language by Apple

Automatic Reference Counting

class BowlingPin {}

func juggle(count: Int) { var left = BowlingPin() if count > 1 { var right = BowlingPin() right = left } // right goes out of scope} // left goes out of scope

Page 101: Intermediate Swift Language by Apple

Ownership

Page 102: Intermediate Swift Language by Apple

Ownership

class Apartment { var tenant: Person?}

Page 103: Intermediate Swift Language by Apple

Ownership

class Apartment { var tenant: Person?}class Person { var home: Apartment?

Page 104: Intermediate Swift Language by Apple

Ownership

class Apartment { var tenant: Person?}class Person { var home: Apartment?

func moveIn(apt: Apartment) { self.home = apt apt.tenant = self }}

Page 105: Intermediate Swift Language by Apple

Ownership

Page 106: Intermediate Swift Language by Apple

Ownership

var renters = ["Elsvette": Person()]

Person

renters

Page 107: Intermediate Swift Language by Apple

Ownership

var renters = ["Elsvette": Person()]var apts = [507: Apartment()]

Person

renters

Apartment

apts

Page 108: Intermediate Swift Language by Apple

Ownership

var renters = ["Elsvette": Person()]var apts = [507: Apartment()]renters["Elsvette"]!.moveIn(apts[507]!)

Person

renters

Apartment

apts

home tenant

Page 109: Intermediate Swift Language by Apple

Ownership

var renters = ["Elsvette": Person()]var apts = [507: Apartment()]renters["Elsvette"]!.moveIn(apts[507]!)

renters["Elsvette"] = nil

Person Apartment

apts

home tenant

Page 110: Intermediate Swift Language by Apple

Ownership

var renters = ["Elsvette": Person()]var apts = [507: Apartment()]renters["Elsvette"]!.moveIn(apts[507]!)

renters["Elsvette"] = nil

Person Apartment

apts

home tenant

Page 111: Intermediate Swift Language by Apple

Ownership

var renters = ["Elsvette": Person()]var apts = [507: Apartment()]renters["Elsvette"]!.moveIn(apts[507]!)

renters["Elsvette"] = nilapts[507] = nil Person Apartment

home tenant

Page 112: Intermediate Swift Language by Apple

Ownership

var renters = ["Elsvette": Person()]var apts = [507: Apartment()]renters["Elsvette"]!.moveIn(apts[507]!)

renters["Elsvette"] = nilapts[507] = nil Person Apartment

home tenant

Page 113: Intermediate Swift Language by Apple

Weak References

class Apartment { !

} class Person { !

!

func moveIn(apt: Apartment) { self.home = apt apt.tenant = self } }

var tenant: Person?

var home: Apartment?

Page 114: Intermediate Swift Language by Apple

Weak References

class Apartment { !

} class Person { !

!

func moveIn(apt: Apartment) { self.home = apt apt.tenant = self } }

var tenant: Person? weak

var home: Apartment? weak

Page 115: Intermediate Swift Language by Apple

Weak References

Person

renters

Apartment

apts

Page 116: Intermediate Swift Language by Apple

Weak References

var renters = ["Elsvette": Person()]var apts = [507: Apartment()]

Person

renters

Apartment

apts

Page 117: Intermediate Swift Language by Apple

Weak References

var renters = ["Elsvette": Person()]var apts = [507: Apartment()]renters["Elsvette"]!.moveIn(apts[507]!)

Person

renters

Apartment

apts

home tenant

Page 118: Intermediate Swift Language by Apple

Weak References

var renters = ["Elsvette": Person()]var apts = [507: Apartment()]renters["Elsvette"]!.moveIn(apts[507]!)

renters["Elsvette"] = nil

Person Apartment

apts

home tenant

Page 119: Intermediate Swift Language by Apple

Weak References

var renters = ["Elsvette": Person()]var apts = [507: Apartment()]renters["Elsvette"]!.moveIn(apts[507]!)

renters["Elsvette"] = nil

Apartment

apts

tenant

Page 120: Intermediate Swift Language by Apple

Weak References

var renters = ["Elsvette": Person()]var apts = [507: Apartment()]renters["Elsvette"]!.moveIn(apts[507]!)

renters["Elsvette"] = nil

Apartment

apts

Page 121: Intermediate Swift Language by Apple

Weak References

var renters = ["Elsvette": Person()]var apts = [507: Apartment()]renters["Elsvette"]!.moveIn(apts[507]!)

renters["Elsvette"] = nilapts[507] = nil

Page 122: Intermediate Swift Language by Apple

Using Weak References

Page 123: Intermediate Swift Language by Apple

Using Weak References

Weak references are optional values

Page 124: Intermediate Swift Language by Apple

Using Weak References

Weak references are optional values

Binding the optional produces a strong reference

if let tenant = apt.tenant { tenant.buzzIn()}

Page 125: Intermediate Swift Language by Apple

Using Weak References

Weak references are optional values

Binding the optional produces a strong reference

if let tenant = apt.tenant { tenant.buzzIn()}

apt.tenant?.buzzIn()

Page 126: Intermediate Swift Language by Apple

Using Weak References

Page 127: Intermediate Swift Language by Apple

Using Weak References

Testing a weak reference alone does not produce a strong reference

if apt.tenant { apt.tenant!.cashRentCheck() apt.tenant!.greet()}

Page 128: Intermediate Swift Language by Apple

Using Weak References

Testing a weak reference alone does not produce a strong reference

Chaining doesn't preserve a strong reference between method invocations

if apt.tenant { apt.tenant!.cashRentCheck() apt.tenant!.greet()}

apt.tenant?.cashRentCheck()apt.tenant?.greet()

Page 129: Intermediate Swift Language by Apple

Same-Lifetime Relationships

Page 130: Intermediate Swift Language by Apple

Same-Lifetime Relationships

class Person { var card: CreditCard?}

Page 131: Intermediate Swift Language by Apple

Same-Lifetime Relationships

class Person { var card: CreditCard?}class CreditCard { holder: Personlet

Page 132: Intermediate Swift Language by Apple

Same-Lifetime Relationships

class Person { var card: CreditCard?}class CreditCard { holder: Personlet

Page 133: Intermediate Swift Language by Apple

Same-Lifetime Relationships

class Person { var card: CreditCard?}class CreditCard { holder: Person

init(holder: Person) { self.holder = holder }}

let

Page 134: Intermediate Swift Language by Apple

Same-Lifetime Relationships

class Person { var card: CreditCard? } class CreditCard { !

!

init(holder: Person) { self.holder = holder } }

let holder: Person

Page 135: Intermediate Swift Language by Apple

Same-Lifetime Relationships

class Person { var card: CreditCard? } class CreditCard { !

!

init(holder: Person) { self.holder = holder } }

let weak holder: Person

Page 136: Intermediate Swift Language by Apple

Same-Lifetime Relationships

class Person { var card: CreditCard? } class CreditCard { !

!

init(holder: Person) { self.holder = holder } }

let weak holder: Person?

Page 137: Intermediate Swift Language by Apple

Same-Lifetime Relationships

class Person { var card: CreditCard? } class CreditCard { !

!

init(holder: Person) { self.holder = holder } }

weak holder: Personvar ?

Page 138: Intermediate Swift Language by Apple

Unowned References

class Person { var card: CreditCard? } class CreditCard { !

!

init(holder: Person) { self.holder = holder } }

holder: Personlet

Page 139: Intermediate Swift Language by Apple

Unowned References

class Person { var card: CreditCard? } class CreditCard { !

!

init(holder: Person) { self.holder = holder } }

holder: Personletunowned

Page 140: Intermediate Swift Language by Apple

Unowned References

Page 141: Intermediate Swift Language by Apple

Unowned References

var renters = ["Elsvette": Person()]

Person

renters

Page 142: Intermediate Swift Language by Apple

Unowned References

var renters = ["Elsvette": Person()]customers["Elsvette"]!.saveCard()

Person

renters

card

CreditCardholder

Page 143: Intermediate Swift Language by Apple

Unowned References

var renters = ["Elsvette": Person()]customers["Elsvette"]!.saveCard()customers["Elsvette"] = nil

Personcard

CreditCardholder

Page 144: Intermediate Swift Language by Apple

Unowned References

var renters = ["Elsvette": Person()]customers["Elsvette"]!.saveCard()customers["Elsvette"] = nil

Page 145: Intermediate Swift Language by Apple

Using Unowned References

Page 146: Intermediate Swift Language by Apple

Using Unowned References

let holder = card.holder

Page 147: Intermediate Swift Language by Apple

Using Unowned References

let holder = card.holdercard.holder.charge(2.19)

Page 148: Intermediate Swift Language by Apple

Strong, Weak, and Unowned References

Page 149: Intermediate Swift Language by Apple

Use strong references from owners to the objects they own

Strong, Weak, and Unowned References

Page 150: Intermediate Swift Language by Apple

Strong, Weak, and Unowned References

Page 151: Intermediate Swift Language by Apple

Strong, Weak, and Unowned References

Use weak references among objects with independent lifetimes

Page 152: Intermediate Swift Language by Apple

Strong, Weak, and Unowned References

Use weak references among objects with independent lifetimes

Page 153: Intermediate Swift Language by Apple

Strong, Weak, and Unowned References

Use weak references among objects with independent lifetimes

Page 154: Intermediate Swift Language by Apple

Strong, Weak, and Unowned References

Page 155: Intermediate Swift Language by Apple

Strong, Weak, and Unowned References

Use unowned references from owned objects with the same lifetime

Page 156: Intermediate Swift Language by Apple

Strong, Weak, and Unowned References

Use unowned references from owned objects with the same lifetime

Page 157: Intermediate Swift Language by Apple

Strong, Weak, and Unowned References

Use unowned references from owned objects with the same lifetime

Page 158: Intermediate Swift Language by Apple

Memory Management

Automatic, safe, predictable

Think about relationships between objects

Model ownership using strong, weak, and unowned references

Page 159: Intermediate Swift Language by Apple

Initialization

Brian Lanier Developer Publications Engineer

Page 160: Intermediate Swift Language by Apple

!

!

Every value must be initialized before it is used

Page 161: Intermediate Swift Language by Apple

!

!

Every value must be initialized before it is used

Page 162: Intermediate Swift Language by Apple

Initialization

var message: String !

Page 163: Intermediate Swift Language by Apple

Initialization

var message: String !

if sessionStarted { message = "Welcome to Intermediate Swift!" } !

println(message)

Page 164: Intermediate Swift Language by Apple

Initialization

var message: String !

if sessionStarted { message = "Welcome to Intermediate Swift!" } !

println(message) // error: variable 'message' used before being initialized

Page 165: Intermediate Swift Language by Apple

Initialization

var message: String !

if sessionStarted { message = "Welcome to Intermediate Swift!" } else { message = "See you next year!" } !

println(message)

Page 166: Intermediate Swift Language by Apple

Initialization

var message: String !

if sessionStarted { message = "Welcome to Intermediate Swift!" } else { message = "See you next year!" } !

println(message)

Welcome to Intermediate Swift!

Page 167: Intermediate Swift Language by Apple

Initializers

Page 168: Intermediate Swift Language by Apple

Initializers

Initializers handle the responsibility of fully initializing an instance

Page 169: Intermediate Swift Language by Apple

Initializers

Initializers handle the responsibility of fully initializing an instance !

init() {…}

!

Page 170: Intermediate Swift Language by Apple

Initializers

Initializers handle the responsibility of fully initializing an instance !

init() {…} !

let instance = MyClass()

Page 171: Intermediate Swift Language by Apple

Initializers

Initializers handle the responsibility of fully initializing an instance !

init( !

let instance = MyClass(

) {…}

)

Page 172: Intermediate Swift Language by Apple

Initializers

Initializers handle the responsibility of fully initializing an instance !

init( !

let instance = MyClass(

luckyNumber: Int, message: String) {…}

)

Page 173: Intermediate Swift Language by Apple

Initializers

Initializers handle the responsibility of fully initializing an instance !

init( !

let instance = MyClass(

luckyNumber: Int, message: String

luckyNumber: 42, message: "Not today"

) {…}

)

Page 174: Intermediate Swift Language by Apple

Structure Initialization

Page 175: Intermediate Swift Language by Apple

Structure Initialization

struct Color { let red, green, blue: Double }

Page 176: Intermediate Swift Language by Apple

Structure Initialization

struct Color { let red, green, blue: Double init(grayScale: Double) { red = grayScale green = grayScale blue = grayScale } }

Page 177: Intermediate Swift Language by Apple

Structure Initialization

struct Color { let red, green, blue: Double init(grayScale: Double) { red = grayScale green = grayScale blue = grayScale } }

Page 178: Intermediate Swift Language by Apple

Structure Initialization

struct Color { let red, green, blue: Double init(grayScale: Double) { green = grayScale blue = grayScale } } // error: variable 'self.red' used before being initialized

Page 179: Intermediate Swift Language by Apple

Structure Initialization

struct Color { let red, green, blue: Double mutating func validateColor() { ... } init(grayScale: Double) { red = grayScale green = grayScale validateColor() blue = grayScale } }

Page 180: Intermediate Swift Language by Apple

Structure Initialization

struct Color { let red, green, blue: Double mutating func validateColor() { ... } init(grayScale: Double) { red = grayScale green = grayScale validateColor() blue = grayScale } }

Page 181: Intermediate Swift Language by Apple

validateColor()

struct Color { let red, green, blue: Double mutating func validateColor() { ... } init(grayScale: Double) { red = grayScale green = grayScale blue = grayScale } } // error: 'self' used before being initialized

Structure Initialization

Page 182: Intermediate Swift Language by Apple

validateColor()

struct Color { let red, green, blue: Double mutating func validateColor() { ... } init(grayScale: Double) { red = grayScale green = grayScale blue = grayScale } } // error: 'self' used before being initialized

self.

Structure Initialization

Page 183: Intermediate Swift Language by Apple

Structure Initialization

struct Color { let red, green, blue: Double mutating func validateColor() { ... } init(grayScale: Double) { red = grayScale green = grayScale blue = grayScale validateColor() } }

Page 184: Intermediate Swift Language by Apple

Memberwise Initializers

struct Color { let red, green, blue: Double }

Page 185: Intermediate Swift Language by Apple

Memberwise Initializers

struct Color { let red, green, blue: Double } !

!

let magenta = Color(red: 1.0, green: 0.0, blue: 1.0)

Page 186: Intermediate Swift Language by Apple

Default Values

struct Color { let red = 0.0, green = 0.0, blue = 0.0 }

Page 187: Intermediate Swift Language by Apple

Default Initializer

struct Color { let red = 0.0, green = 0.0, blue = 0.0 } !

let black = Color()

Page 188: Intermediate Swift Language by Apple

Class Initialization

Page 189: Intermediate Swift Language by Apple

Class Initialization

class Car { var paintColor: Color init(color: Color) { paintColor = color } }

Page 190: Intermediate Swift Language by Apple

Class Initialization

class Car { var paintColor: Color init(color: Color) { paintColor = color } }

Page 191: Intermediate Swift Language by Apple

Class Initialization

class Car { var paintColor: Color init(color: Color) { paintColor = color } } !

class RaceCar: Car { var hasTurbo: Bool !

init(color: Color, turbo: Bool) { hasTurbo = turbo super.init(color: color) } }

Page 192: Intermediate Swift Language by Apple

Class Initialization

class Car { var paintColor: Color init(color: Color) { paintColor = color } } !

class RaceCar: Car { var hasTurbo: Bool !

init(color: Color, turbo: Bool) { hasTurbo = turbo super.init(color: color) } }

Page 193: Intermediate Swift Language by Apple

Class Initialization

class Car { var paintColor: Color init(color: Color) { paintColor = color } } !

class RaceCar: Car { var hasTurbo: Bool !

init(color: Color, turbo: Bool) { hasTurbo = turbo super.init(color: color) } }

Page 194: Intermediate Swift Language by Apple

Class Initialization

class Car { var paintColor: Color init(color: Color) { paintColor = color } } !

class RaceCar: Car { var hasTurbo: Bool !

init(color: Color, turbo: Bool) { hasTurbo = turbo super.init(color: color) } }

Page 195: Intermediate Swift Language by Apple

Class Initialization

class Car { var paintColor: Color init(color: Color) { paintColor = color } } !

class RaceCar: Car { var hasTurbo: Bool !

init(color: Color, turbo: Bool) { hasTurbo = turbo super.init(color: color) } }

Page 196: Intermediate Swift Language by Apple

Class Initialization

class Car { var paintColor: Color init(color: Color) { paintColor = color !

class RaceCar: Car { var hasTurbo: Bool !

init(color: Color, turbo: Bool) { hasTurbo = turbo super.init(color: color)

}}

}}

Page 197: Intermediate Swift Language by Apple

Class Initialization

class Car { var paintColor: Color init(color: Color) { paintColor = color !

class RaceCar: Car { var hasTurbo: Bool !

init(color: Color, turbo: Bool) { hasTurbo = turbo super.init(color: color)

}}

}}

Page 198: Intermediate Swift Language by Apple

Class Initialization

class Car { var paintColor: Color init(color: Color) { paintColor = color !

class RaceCar: Car { var hasTurbo: Bool !

init(color: Color, turbo: Bool) { super.init(color: color) hasTurbo = turbo

}}

}}

Page 199: Intermediate Swift Language by Apple

Class Initialization

class Car { var paintColor: Color init(color: Color) { paintColor = color } } !

class RaceCar: Car { var hasTurbo: Bool !

init(color: Color, turbo: Bool) { super.init(color: color) hasTurbo = turbo } }

Page 200: Intermediate Swift Language by Apple

Class Initialization

class Car { var paintColor: Color func fillGasTank() {...} init(color: Color) { paintColor = color fillGasTank() } } !

class RaceCar: Car { var hasTurbo: Bool override func fillGasTank() { ... } init(color: Color, turbo: Bool) { super.init(color: color) hasTurbo = turbo } }

Page 201: Intermediate Swift Language by Apple

Class Initialization

class Car { var paintColor: Color func fillGasTank() {...} init(color: Color) { paintColor = color fillGasTank() } } !

class RaceCar: Car { var hasTurbo: Bool override func fillGasTank() { ... } init(color: Color, turbo: Bool) { super.init(color: color) hasTurbo = turbo } }

Page 202: Intermediate Swift Language by Apple

Class Initialization

class Car { var paintColor: Color func fillGasTank() {...} init(color: Color) { paintColor = color fillGasTank() } } !

class RaceCar: Car { var hasTurbo: Bool override func fillGasTank() { ... } init(color: Color, turbo: Bool) { super.init(color: color) hasTurbo = turbo } }

Page 203: Intermediate Swift Language by Apple

Class Initialization

class Car { var paintColor: Color func fillGasTank() {...} init(color: Color) { paintColor = color fillGasTank() } } !

class RaceCar: Car { var hasTurbo: Bool override func fillGasTank() { ... } init(color: Color, turbo: Bool) { super.init(color: color) hasTurbo = turbo } }

Page 204: Intermediate Swift Language by Apple

Class Initialization

class Car { var paintColor: Color func fillGasTank() {...} init(color: Color) { paintColor = color fillGasTank() } } !

class RaceCar: Car { var hasTurbo: Bool override func fillGasTank() { ... } init(color: Color, turbo: Bool) { super.init(color: color) hasTurbo = turbo } }

Page 205: Intermediate Swift Language by Apple

Class Initialization

class Car { var paintColor: Color func fillGasTank() {...} init(color: Color) { paintColor = color fillGasTank() } } !

class RaceCar: Car { var hasTurbo: Bool override func fillGasTank() { ... } init(color: Color, turbo: Bool) { super.init(color: color) hasTurbo = turbo } }

Page 206: Intermediate Swift Language by Apple

Class Initialization

class Car { var paintColor: Color func fillGasTank() {...} init(color: Color) { paintColor = color fillGasTank() !

class RaceCar: Car { var hasTurbo: Bool override func fillGasTank() { ... } init(color: Color, turbo: Bool) { super.init(color: color) hasTurbo = turbo

Page 207: Intermediate Swift Language by Apple

Class Initialization

class Car { var paintColor: Color func fillGasTank() {...} init(color: Color) { paintColor = color fillGasTank() } } !

class RaceCar: Car { var hasTurbo: Bool override func fillGasTank() { ... } init(color: Color, turbo: Bool) { super.init(color: color) hasTurbo = turbo } } // error: property 'hasTurbo' not initialized at super.init call

Page 208: Intermediate Swift Language by Apple

Class Initialization

class Car { var paintColor: Color func fillGasTank() {...} init(color: Color) { paintColor = color fillGasTank() } } !

class RaceCar: Car { var hasTurbo: Bool override func fillGasTank() { ... } init(color: Color, turbo: Bool) { hasTurbo = turbo super.init(color: color) } }

super.init(color: color)hasTurbo = turbo

Page 209: Intermediate Swift Language by Apple

Class Initialization

class Car { var paintColor: Color func fillGasTank() {...} init(color: Color) { paintColor = color fillGasTank() } } !

class RaceCar: Car { var hasTurbo: Bool override func fillGasTank() { ... } init(color: Color, turbo: Bool) { hasTurbo = turbo super.init(color: color) } }

super.init(color: color)hasTurbo = turbo

Page 210: Intermediate Swift Language by Apple

Initializer DelegationBaseClass

SuperClass

Class

Page 211: Intermediate Swift Language by Apple

Initializer DelegationBaseClass

SuperClass

Class

Designated

Designated

Designated Designated

Page 212: Intermediate Swift Language by Apple

Initializer DelegationBaseClass

SuperClass

Class

Designated

Designated

Designated Designated

Convenience Convenience

Convenience Convenience

Convenience

Page 213: Intermediate Swift Language by Apple

Convenience Initializers

class RaceCar: Car { var hasTurbo: Bool init(color: Color, turbo: Bool) { hasTurbo = turbo super.init(color: color) } !

!

!

!

!

!

!

}

Page 214: Intermediate Swift Language by Apple

Convenience Initializers

class RaceCar: Car { var hasTurbo: Bool init(color: Color, turbo: Bool) { hasTurbo = turbo super.init(color: color) } !

init(color: Color) { self.init(color: color, turbo: true) } !

!

!

}

Page 215: Intermediate Swift Language by Apple

Convenience Initializers

class RaceCar: Car { var hasTurbo: Bool init(color: Color, turbo: Bool) { hasTurbo = turbo super.init(color: color) } !

init(color: Color) { self.init(color: color, turbo: true) } !

!

!

}

Page 216: Intermediate Swift Language by Apple

Convenience Initializers

class RaceCar: Car { var hasTurbo: Bool init(color: Color, turbo: Bool) { hasTurbo = turbo super.init(color: color) } !

init(color: Color) { self.init(color: color, turbo: true) } !

!

!

}

Page 217: Intermediate Swift Language by Apple

class RaceCar: Car { var hasTurbo: Bool init(color: Color, turbo: Bool) { hasTurbo = turbo super.init(color: color) } !

self.init(color: color, turbo: true) } !

!

!

}

init(color: Color) {

Convenience Initializers

Page 218: Intermediate Swift Language by Apple

class RaceCar: Car { var hasTurbo: Bool init(color: Color, turbo: Bool) { hasTurbo = turbo super.init(color: color) } !

self.init(color: color, turbo: true) } !

!

!

}

convenience init(color: Color) {

Convenience Initializers

Page 219: Intermediate Swift Language by Apple

Convenience Initializers

class RaceCar: Car { var hasTurbo: Bool init(color: Color, turbo: Bool) { hasTurbo = turbo super.init(color: color) } !

convenience init(color: Color) { self.init(color: color, turbo: true) } !

convenience init() { self.init(color: Color(gray: 0.4)) } }

Page 220: Intermediate Swift Language by Apple

Convenience Initializers

class RaceCar: Car { var hasTurbo: Bool init(color: Color, turbo: Bool) { hasTurbo = turbo super.init(color: color) } !

convenience init(color: Color) { self.init(color: color, turbo: true) } !

convenience init() { self.init(color: Color(gray: 0.4)) } }

Page 221: Intermediate Swift Language by Apple

Convenience Initializers

class RaceCar: Car { var hasTurbo: Bool init(color: Color, turbo: Bool) { hasTurbo = turbo super.init(color: color) } !

convenience init(color: Color) { self.init(color: color, turbo: true) } !

convenience init() { self.init(color: Color(gray: 0.4)) } }

Page 222: Intermediate Swift Language by Apple

Convenience Initializers

class RaceCar: Car { var hasTurbo: Bool init(color: Color, turbo: Bool) { hasTurbo = turbo super.init(color: color) } !

convenience init(color: Color) { self.init(color: color, turbo: true) } !

convenience init() { self.init(color: Color(gray: 0.4)) } }

Page 223: Intermediate Swift Language by Apple

Convenience Initializers

class RaceCar: Car { var hasTurbo: Bool init(color: Color, turbo: Bool) { hasTurbo = turbo super.init(color: color) } !

convenience init(color: Color) { self.init(color: color, turbo: true) } !

convenience init() { self.init(color: Color(gray: 0.4)) } }

Page 224: Intermediate Swift Language by Apple

Convenience Initializers

class RaceCar: Car { var hasTurbo: Bool init(color: Color, turbo: Bool) { hasTurbo = turbo super.init(color: color) } !

convenience init(color: Color) { self.init(color: color, turbo: true) } !

convenience init() { self.init(color: Color(gray: 0.4)) } }

Page 225: Intermediate Swift Language by Apple

Initializer Inheritance

class FormulaOne: RaceCar { let minimumWeight = 642

Page 226: Intermediate Swift Language by Apple

Initializer Inheritance

class FormulaOne: RaceCar { let minimumWeight = 642 // inherited from RaceCar init(color: Color, turbo: Bool) { hasTurbo = turbo super.init(color: color) } convenience init(color: Color) { self.init(color: color, turbo: true) } convenience init() { self.init(color: Color(gray: 0.4)) } }

Page 227: Intermediate Swift Language by Apple

Initializer Inheritance

class FormulaOne: RaceCar { let minimumWeight = 642 // inherited from RaceCar init(color: Color, turbo: Bool) { hasTurbo = turbo super.init(color: color) } convenience init(color: Color) { self.init(color: color, turbo: true) } convenience init() { self.init(color: Color(gray: 0.4)) } }

Page 228: Intermediate Swift Language by Apple

Initializer Inheritance

class FormulaOne: RaceCar { let minimumWeight = 642 init(color: Color) { super.init(color: color, turbo: false) } !

!

!

}

Page 229: Intermediate Swift Language by Apple

Initializer Inheritance

class FormulaOne: RaceCar { let minimumWeight = 642 init(color: Color) { super.init(color: color, turbo: false) } !

// not inherited from RaceCar init(color: Color, turbo: Bool) convenience init() }

Page 230: Intermediate Swift Language by Apple

Lazy Properties

Page 231: Intermediate Swift Language by Apple

Lazy Properties

class Game { var multiplayerManager = MultiplayerManager() var singlePlayer: Player? func beginGameWithPlayers(players: Player...) { !

!

!

!

!

!

} }

Page 232: Intermediate Swift Language by Apple

Lazy Properties

class Game { var multiplayerManager = MultiplayerManager() var singlePlayer: Player? func beginGameWithPlayers(players: Player...) { if players.count == 1 { singlePlayer = players[0] } !

!

!

!

} }

Page 233: Intermediate Swift Language by Apple

Lazy Properties

class Game { var multiplayerManager = MultiplayerManager() var singlePlayer: Player? func beginGameWithPlayers(players: Player...) { if players.count == 1 { singlePlayer = players[0] } else { for player in players { multiplayerManager.addPlayer(player) } } } }

Page 234: Intermediate Swift Language by Apple

class Game { var singlePlayer: Player? func beginGameWithPlayers(players: Player...) { if players.count == 1 { singlePlayer = players[0] } else { for player in players { multiplayerManager.addPlayer(player) } } } }

var multiplayerManager = MultiplayerManager()

Lazy Properties

Page 235: Intermediate Swift Language by Apple

class Game { var singlePlayer: Player? func beginGameWithPlayers(players: Player...) { if players.count == 1 { singlePlayer = players[0] } else { for player in players { multiplayerManager.addPlayer(player) } } } }

@lazy var multiplayerManager = MultiplayerManager()

Lazy Properties

Page 236: Intermediate Swift Language by Apple

Deinitialization

Page 237: Intermediate Swift Language by Apple

Deinitialization

class FileHandle { let fileDescriptor: FileDescriptor init(path: String) { fileDescriptor = openFile(path) } !

!

!

}

Page 238: Intermediate Swift Language by Apple

Deinitialization

class FileHandle { let fileDescriptor: FileDescriptor init(path: String) { fileDescriptor = openFile(path) } deinit { closeFile(fileDescriptor) } }

Page 239: Intermediate Swift Language by Apple

Initialization

Page 240: Intermediate Swift Language by Apple

Initialization

Initialize all values before you use them

Set all stored properties first, then call super.init

Page 241: Intermediate Swift Language by Apple

Initialization

Initialize all values before you use them

Set all stored properties first, then call super.init

Designated initializers only delegate up

Convenience initializers only delegate across

Page 242: Intermediate Swift Language by Apple

Initialization

Initialize all values before you use them

Set all stored properties first, then call super.init

Designated initializers only delegate up

Convenience initializers only delegate across

Deinitializers are there… if you need them

Page 243: Intermediate Swift Language by Apple

Closures

Joe Groff Swift Compiler Engineer

Page 244: Intermediate Swift Language by Apple

Closures

var clients = ["Pestov", "Buenaventura", "Sreeram", "Babbage"] !

clients.sort( !

!

!

println(clients)

Page 245: Intermediate Swift Language by Apple

Closures

var clients = ["Pestov", "Buenaventura", "Sreeram", "Babbage"] !

clients.sort( !

!

!

println(clients)

{

})

Page 246: Intermediate Swift Language by Apple

Closures

var clients = ["Pestov", "Buenaventura", "Sreeram", "Babbage"] !

clients.sort( !

!

!

println(clients)

{(a: String, b: String) -> Bool

})

Page 247: Intermediate Swift Language by Apple

Closures

var clients = ["Pestov", "Buenaventura", "Sreeram", "Babbage"] !

clients.sort( !

!

!

println(clients)

{(a: String, b: String) -> Bool in

})

Page 248: Intermediate Swift Language by Apple

Closures

var clients = ["Pestov", "Buenaventura", "Sreeram", "Babbage"] !

clients.sort( !

!

!

println(clients)

{(a: String, b: String) -> Bool inreturn a < b

})

Page 249: Intermediate Swift Language by Apple

Closures

var clients = ["Pestov", "Buenaventura", "Sreeram", "Babbage"] !

clients.sort( !

!

!

println(clients)

in{(a: String, b: String) -> Boolreturn a < b

})

Page 250: Intermediate Swift Language by Apple

Closures

var clients = ["Pestov", "Buenaventura", "Sreeram", "Babbage"] !

clients.sort( !

!

!

println(clients)

in{(a: String, b: String) -> Boolreturn a < b

})

[Babbage, Buenaventura, Pestov, Sreeram]

Page 251: Intermediate Swift Language by Apple

var clients = ["Pestov", "Buenaventura", "Sreeram", "Babbage"] !

clients.sort( !

!

!

println(clients)

in{(a: String, b: String) -> Bool

})

Closures

Page 252: Intermediate Swift Language by Apple

var clients = ["Pestov", "Buenaventura", "Sreeram", "Babbage"] !

clients.sort( !

!

!

println(clients)

in{(a: String, b: String) -> Boolreturn a > b

})

Closures

[Sreeram, Pestov, Buenaventura, Babbage]

Page 253: Intermediate Swift Language by Apple

var clients = ["Pestov", "Buenaventura", "Sreeram", "Babbage"] !

clients.sort( !

!

!

println(clients)

Closures

in{(a: String, b: String) -> Bool

})

Page 254: Intermediate Swift Language by Apple

var clients = ["Pestov", "Buenaventura", "Sreeram", "Babbage"] !

clients.sort( !

!

!

println(clients)

Closures

[Pestov, Sreeram, Babbage, Buenaventura]

in{(a: String, b: String) -> Boolreturn countElements(a) < countElements(b)

})

Page 255: Intermediate Swift Language by Apple

var clients = ["Pestov", "Buenaventura", "Sreeram", "Babbage"] !

clients.sort( !

!

!

println(clients)

in{(a: String, b: String) -> Bool

})

Closures

Page 256: Intermediate Swift Language by Apple

var clients = ["Pestov", "Buenaventura", "Sreeram", "Babbage"] !

clients.sort( !

!

!

println(clients)

in{(a: String, b: String) -> Bool

})

Closures

return a < b

Page 257: Intermediate Swift Language by Apple

var clients = ["Pestov", "Buenaventura", "Sreeram", "Babbage"] !

clients.sort( !

!

!

println(clients)

in{(a: String, b: String) -> Bool

})

Closures

return a < b

Page 258: Intermediate Swift Language by Apple

Type Inference

var clients = ["Pestov", "Buenaventura", "Sreeram", "Babbage"] !

clients.sort( !

!

!

println(clients)

in{(a: String, b: String) -> Bool

})return a < b

Page 259: Intermediate Swift Language by Apple

Type Inference

var clients = ["Pestov", "Buenaventura", "Sreeram", "Babbage"] !

clients.sort( !

!

!

println(clients)

in{(a: String, b: String) -> Bool

})

sortreturn a < b

Page 260: Intermediate Swift Language by Apple

Type Inference

struct Array<T> { func sort(order: (T, T) -> Bool) }

Page 261: Intermediate Swift Language by Apple

Type Inference

struct Array<String> { func sort(order: (String, String) -> Bool) }

Page 262: Intermediate Swift Language by Apple

Type Inference

struct Array<String> { func sort(order: (String, String) -> Bool) }

{( : String : String) -> Boolreturn

})a < b

inclients.sort( a , b

Page 263: Intermediate Swift Language by Apple

Type Inference

struct Array<String> { func sort(order: (String, String) -> Bool) }

{return

})a < b

inclients.sort( a, b

Page 264: Intermediate Swift Language by Apple

Implicit Return

{return

})a < b

inclients.sort( a, b

Page 265: Intermediate Swift Language by Apple

Implicit Return

{ inclients.sort( a, b a < b })

Page 266: Intermediate Swift Language by Apple

a

Implicit Arguments

{ inclients.sort( a, b < })b

Page 267: Intermediate Swift Language by Apple

Implicit Arguments

{clients.sort( < })$0 $1

Page 268: Intermediate Swift Language by Apple

Trailing Closures

clients.sort $1$0{ < })(

Page 269: Intermediate Swift Language by Apple

Trailing Closures

clients.sort $1$0{ < }

Page 270: Intermediate Swift Language by Apple

Functional Programming

Page 271: Intermediate Swift Language by Apple

Functional Programming

println(words)

aaardvarkaardwolf…

Page 272: Intermediate Swift Language by Apple

Functional Programming

println(words.filter { $0.hasSuffix("gry") })

Page 273: Intermediate Swift Language by Apple

Functional Programming

println(words.filter { $0.hasSuffix("gry") })

angryhungry

Page 274: Intermediate Swift Language by Apple

Functional Programming

println(words.filter { $0.hasSuffix("gry") } .map { $0.uppercaseString })

Page 275: Intermediate Swift Language by Apple

Functional Programming

println(words.filter { $0.hasSuffix("gry") } .map { $0.uppercaseString })

ANGRYHUNGRY

Page 276: Intermediate Swift Language by Apple

Functional Programming

println(words.filter { $0.hasSuffix("gry") } .map { $0.uppercaseString } .reduce("HULK") { "\($0) \($1)" })

Page 277: Intermediate Swift Language by Apple

Functional Programming

println(words.filter { $0.hasSuffix("gry") } .map { $0.uppercaseString } .reduce("HULK") { "\($0) \($1)" })

HULK ANGRY HUNGRY

Page 278: Intermediate Swift Language by Apple

Functional Programming

println(words.filter { $0.hasSuffix("gry") } .map { $0.uppercaseString } .reduce("HULK") { "\($0) \($1)" })

HULK ANGRY HUNGRY

Page 279: Intermediate Swift Language by Apple

Functional Programming

println(words.filter { $0.hasSuffix("gry") } .map { $0.uppercaseString } .reduce("HULK") { "\($0) \($1)" })

Page 280: Intermediate Swift Language by Apple

Functional Programming

println(

GRR!! HULK ANGRY HUNGRY!!!

words.filter { $0.hasSuffix("gry") } .map { $0.uppercaseString } .reduce("HULK") { "\($0) \($1)" } )

"GRR!! " +

+ "!!!"

Page 281: Intermediate Swift Language by Apple

Captures

Page 282: Intermediate Swift Language by Apple

Captures

func sum(numbers: Int[]) { var sum = 0

numbers.map {

Page 283: Intermediate Swift Language by Apple

Captures

func sum(numbers: Int[]) { var sum = 0

numbers.map { sum += $0 }

Page 284: Intermediate Swift Language by Apple

Captures

func sum(numbers: Int[]) { var sum = 0

numbers.map { sum += $0 }

Page 285: Intermediate Swift Language by Apple

Captures

func sum(numbers: Int[]) { var sum = 0

numbers.map { sum += $0 }

Page 286: Intermediate Swift Language by Apple

Captures

func sum(numbers: Int[]) { var sum = 0

numbers.map { sum += $0 }

return sum}

Page 287: Intermediate Swift Language by Apple

Function Values—Closures

!

!

!

numbers.map { sum += $0 }

Page 288: Intermediate Swift Language by Apple

!

!

!

numbers.map

Function Values—Functions

println($0){

}

Page 289: Intermediate Swift Language by Apple

!

!

!

numbers.map (println)

Function Values—Functions

Page 290: Intermediate Swift Language by Apple

!

!

var indexes = NSMutableIndexSet() numbers.map !

Function Values—Methods

indexes.addIndex($0){

}

Page 291: Intermediate Swift Language by Apple

!

!

var indexes = NSMutableIndexSet() numbers.map !

(indexes.addIndex)

Function Values—Methods

Page 292: Intermediate Swift Language by Apple

Closures Are ARC Objects

Page 293: Intermediate Swift Language by Apple

Closures Are ARC Objects

var onTemperatureChange: (Int) -> Void = {}onTempChange

Page 294: Intermediate Swift Language by Apple

Closures Are ARC Objects

var onTemperatureChange: (Int) -> Void = {}

func logTemperatureDifferences(initial: Int) { var prev = initial

onTempChange

prev

Page 295: Intermediate Swift Language by Apple

Closures Are ARC Objects

var onTemperatureChange: (Int) -> Void = {}

func logTemperatureDifferences(initial: Int) { var prev = initial onTemperatureChange = { next in println("Changed \(next - prev)°F") prev = next }

{...}

onTempChange

prev

Page 296: Intermediate Swift Language by Apple

Closures Are ARC Objects

var onTemperatureChange: (Int) -> Void = {}

func logTemperatureDifferences(initial: Int) { var prev = initial onTemperatureChange = { next in println("Changed \(next - prev)°F") prev = next }} // scope ends

{...}

onTempChange

prev

Page 297: Intermediate Swift Language by Apple

Functions Are ARC Objects

var onTemperatureChange: (Int) -> Void = {}

func logTemperatureDifferences(initial: Int) { var prev = initial func log(next: Int) { println("Changed \(next - prev)°F") prev = next }

onTempChange

Page 298: Intermediate Swift Language by Apple

Functions Are ARC Objects

var onTemperatureChange: (Int) -> Void = {}

func logTemperatureDifferences(initial: Int) { var prev = initial func log(next: Int) { println("Changed \(next - prev)°F") prev = next }

log

onTempChange

prev

Page 299: Intermediate Swift Language by Apple

Functions Are ARC Objects

var onTemperatureChange: (Int) -> Void = {}

func logTemperatureDifferences(initial: Int) { var prev = initial func log(next: Int) { println("Changed \(next - prev)°F") prev = next }

onTemperatureChange = log

log

onTempChange

prev

Page 300: Intermediate Swift Language by Apple

Functions Are ARC Objects

var onTemperatureChange: (Int) -> Void = {}

func logTemperatureDifferences(initial: Int) { var prev = initial func log(next: Int) { println("Changed \(next - prev)°F") prev = next }

onTemperatureChange = log} // scope ends

log

onTempChange

prev

Page 301: Intermediate Swift Language by Apple

Ownership of Captures

Page 302: Intermediate Swift Language by Apple

Ownership of Captures

class TemperatureNotifier { var onChange: (Int) -> Void = {}

Page 303: Intermediate Swift Language by Apple

Ownership of Captures

class TemperatureNotifier { var onChange: (Int) -> Void = {} var currentTemp = 72

init() { onChange = { temp in

} }}

currentTemp = temp

Page 304: Intermediate Swift Language by Apple

Ownership of Captures

class TemperatureNotifier { var onChange: (Int) -> Void = {} var currentTemp = 72

init() { onChange = { temp in

} }}

{...}

TempNotifier

currentTemp = temp

Page 305: Intermediate Swift Language by Apple

Ownership of Captures

class TemperatureNotifier { var onChange: (Int) -> Void = {} var currentTemp = 72

init() { onChange = { temp in

} }}

{...}

TempNotifier

currentTemp = tempself.self

Page 306: Intermediate Swift Language by Apple

Ownership of Captures

class TemperatureNotifier { var onChange: (Int) -> Void = {} var currentTemp = 72

init() { onChange = { temp in

} }}

{...}

TempNotifier

currentTemp = tempself.self

onChange

Page 307: Intermediate Swift Language by Apple

Ownership of Captures

class TemperatureNotifier { var onChange: (Int) -> Void = {} var currentTemp = 72

init() { onChange = { temp in

} }}

{...}

TempNotifier

currentTemp = tempself.self

onChange

Page 308: Intermediate Swift Language by Apple

Ownership of Captures

class TemperatureNotifier { var onChange: (Int) -> Void = {} var currentTemp = 72

init() { onChange = { temp in

} }}

{...}

TempNotifier

self

onChange

currentTemp = temp// error: requires explicit 'self'

Page 309: Intermediate Swift Language by Apple

class TempNotifier { var onChange: (Int) -> Void = {} var currentTemp = 72 !

init() {onChange = { temp in

Ownership of Captures

currentTemp = tempself. } } }

Page 310: Intermediate Swift Language by Apple

class TempNotifier { var onChange: (Int) -> Void = {} var currentTemp = 72 !

init() {

onChange = { temp inunowned let uSelf = self

Ownership of Captures

currentTemp = tempself. } } }

Page 311: Intermediate Swift Language by Apple

class TempNotifier { var onChange: (Int) -> Void = {} var currentTemp = 72 !

init() {

onChange = { temp inunowned let uSelf = self

Ownership of Captures

currentTemp = temp } } }

uSelf.

Page 312: Intermediate Swift Language by Apple

Capture Lists

class TempNotifier { var onChange: (Int) -> Void = {} var currentTemp = 72 !

init() {

currentTemp = tempself. } } }

onChange = { temp in

Page 313: Intermediate Swift Language by Apple

Capture Lists

class TempNotifier { var onChange: (Int) -> Void = {} var currentTemp = 72 !

init() {

currentTemp = tempself. } } }

onChange = {[unowned self] temp in

Page 314: Intermediate Swift Language by Apple

Capture Lists

class TempNotifier { var onChange: (Int) -> Void = {} var currentTemp = 72 !

init() {

currentTemp = tempself. } } }

onChange = {[unowned self] temp in {...}

TempNotifier

self

onChange

Page 315: Intermediate Swift Language by Apple

Closures

Page 316: Intermediate Swift Language by Apple

Closures

Concise, expressive syntax

Page 317: Intermediate Swift Language by Apple

Closures

Concise, expressive syntax

Simple memory model

Page 318: Intermediate Swift Language by Apple

Closures

Concise, expressive syntax

Simple memory model

Supports functional programming idioms

Page 319: Intermediate Swift Language by Apple

Pattern Matching

Joe Groff Swift Compiler Engineer

Page 320: Intermediate Swift Language by Apple

func describe(value: switch value { case println("the loneliest number that you'll ever do") case println("can be as bad as one") default: println("just some number") } }

Switch

Int) {

1:

2:

Page 321: Intermediate Swift Language by Apple

func describe(value: switch value { case println("the loneliest number that you'll ever do") case println("can be as bad as one") default: println("just some number") } }

Switch

"two"

"one"

String) {

:

:

Page 322: Intermediate Swift Language by Apple

func describe(value: switch value { case println("a few") case println("a lot") default: println("a ton") } }

:

:

String

"two"

"one"

Switch

) {

Page 323: Intermediate Swift Language by Apple

func describe(value: switch value { case println("a few") case println("a lot") default: println("a ton") } }

:

:5...12

0...4

Int

Switch

) {

Page 324: Intermediate Swift Language by Apple

enum TrainStatus { case OnTime case Delayed

Enumerations

}

Page 325: Intermediate Swift Language by Apple

enum TrainStatus { case OnTime case Delayed

Enumerations

}(Int)

Page 326: Intermediate Swift Language by Apple

switch trainStatus { case .OnTime: println("on time") case .Delayed println("delayed }

Enumerations

:")

Page 327: Intermediate Swift Language by Apple

switch trainStatus { case .OnTime: println("on time") case .Delayed println("delayed }

(let minutes)

Enumerations

:")

Page 328: Intermediate Swift Language by Apple

switch trainStatus { case .OnTime: println("on time") case .Delayed println("delayed }

by \(minutes) minutes(let minutes)

Enumerations

:")

Page 329: Intermediate Swift Language by Apple

switch trainStatus { case .OnTime: println("on time") case .Delayed println("delayed }

println("let's take \(minutes) and come back")// error: use of unresolved identifier 'minutes'

by \(minutes) minutes(let minutes)

Enumerations

:")

Page 330: Intermediate Swift Language by Apple

switch trainStatus { case .OnTime: println("on time") case .Delayed println("delayed }

Patterns

:")

(let minutes) by \(minutes) minutes

Page 331: Intermediate Swift Language by Apple

switch trainStatus { case .OnTime: println("on time") case .Delayed println("delayed }

Patterns

:")

(let minutes) by \(minutes) minutes

Page 332: Intermediate Swift Language by Apple

switch trainStatus { case .OnTime: println("on time") case .Delayed println("delayed }

Patterns

:")

(let minutes) by \(minutes) minutes

Page 333: Intermediate Swift Language by Apple

switch trainStatus { case .OnTime: println("on time")

Patterns Compose

Page 334: Intermediate Swift Language by Apple

switch trainStatus { case .OnTime: println("on time")

Patterns Compose

case .Delayed(1): println("nearly on time")

Page 335: Intermediate Swift Language by Apple

switch trainStatus { case .OnTime: println("on time")

Patterns Compose

case .Delayed(1): println("nearly on time") case .Delayed(2...10): println("almost on time, I swear")

Page 336: Intermediate Swift Language by Apple

switch trainStatus { case .OnTime: println("on time")

Patterns Compose

case .Delayed(1): println("nearly on time") case .Delayed(2...10): println("almost on time, I swear") case .Delayed(_): println("it'll get here when it's ready")

Page 337: Intermediate Swift Language by Apple

enum VacationStatus { case Traveling(TrainStatus) case Relaxing(daysLeft: Int) }

Patterns Compose

Page 338: Intermediate Swift Language by Apple

Patterns Compose

Page 339: Intermediate Swift Language by Apple

switch vacationStatus {

Patterns Compose

Page 340: Intermediate Swift Language by Apple

switch vacationStatus { case .Traveling(.OnTime): tweet("Train's on time! Can't wait to get there!")

Patterns Compose

Page 341: Intermediate Swift Language by Apple

switch vacationStatus { case .Traveling(.OnTime): tweet("Train's on time! Can't wait to get there!") case .Traveling(.Delayed(1...15)): tweet("Train is delayed.")

Patterns Compose

Page 342: Intermediate Swift Language by Apple

switch vacationStatus { case .Traveling(.OnTime): tweet("Train's on time! Can't wait to get there!") case .Traveling(.Delayed(1...15)): tweet("Train is delayed.") case .Traveling(.Delayed(_)): tweet("OMG when will this train ride end #railfail")

Patterns Compose

Page 343: Intermediate Swift Language by Apple

Type Patterns

Page 344: Intermediate Swift Language by Apple

func tuneUp(car: Car) { switch car {

Type Patterns

Page 345: Intermediate Swift Language by Apple

func tuneUp(car: Car) { switch car { case let formulaOne as FormulaOne:

Type Patterns

Page 346: Intermediate Swift Language by Apple

func tuneUp(car: Car) { switch car { case let formulaOne as FormulaOne:

Type Patterns

Page 347: Intermediate Swift Language by Apple

func tuneUp(car: Car) { switch car { case let formulaOne as FormulaOne:

Type Patterns

Page 348: Intermediate Swift Language by Apple

func tuneUp(car: Car) { switch car { case let formulaOne as FormulaOne: formulaOne.enterPit()

Type Patterns

Page 349: Intermediate Swift Language by Apple

func tuneUp(car: Car) { switch car { case let formulaOne as FormulaOne: formulaOne.enterPit() case let raceCar as RaceCar: if raceCar.hasTurbo { raceCar.tuneTurbo() }

Type Patterns

Page 350: Intermediate Swift Language by Apple

func tuneUp(car: Car) { switch car { case let formulaOne as FormulaOne: formulaOne.enterPit() case let raceCar as RaceCar: if raceCar.hasTurbo { raceCar.tuneTurbo() } fallthrough

Type Patterns

Page 351: Intermediate Swift Language by Apple

func tuneUp(car: Car) { switch car { case let formulaOne as FormulaOne: formulaOne.enterPit() case let raceCar as RaceCar: if raceCar.hasTurbo { raceCar.tuneTurbo() } fallthrough default: car.checkOil() car.pumpTires() }}

Type Patterns

Page 352: Intermediate Swift Language by Apple

Tuple Patterns

Page 353: Intermediate Swift Language by Apple

let color = (1.0, 1.0, 1.0, 1.0)switch color { case (0.0, 0.5...1.0, let blue, _): println("Green and \(blue * 100)% blue")

Tuple Patterns

Page 354: Intermediate Swift Language by Apple

let color = (1.0, 1.0, 1.0, 1.0)switch color { case (0.0, 0.5...1.0, let blue, _): println("Green and \(blue * 100)% blue")

Tuple Patterns

Page 355: Intermediate Swift Language by Apple

let color = (1.0, 1.0, 1.0, 1.0)switch color { case (0.0, 0.5...1.0, let blue, _): println("Green and \(blue * 100)% blue")

Tuple Patterns

Page 356: Intermediate Swift Language by Apple

let color = (1.0, 1.0, 1.0, 1.0)switch color { case (0.0, 0.5...1.0, let blue, _): println("Green and \(blue * 100)% blue")

Tuple Patterns

Page 357: Intermediate Swift Language by Apple

let color = (1.0, 1.0, 1.0, 1.0)switch color { case (0.0, 0.5...1.0, let blue, _): println("Green and \(blue * 100)% blue")

Tuple Patterns

Page 358: Intermediate Swift Language by Apple

let color = (1.0, 1.0, 1.0, 1.0)switch color { case (0.0, 0.5...1.0, let blue, _): println("Green and \(blue * 100)% blue")

Tuple Patterns

Page 359: Intermediate Swift Language by Apple

let color = (1.0, 1.0, 1.0, 1.0)switch color { case (0.0, 0.5...1.0, let blue, _): println("Green and \(blue * 100)% blue")

case let (r, g, b, 1.0) where r == g && g == b: println("Opaque grey \(r * 100)%")

Tuple Patterns

Page 360: Intermediate Swift Language by Apple

Validating a Property List

Page 361: Intermediate Swift Language by Apple

Validating a Property List

func stateFromPlist(list: Dictionary<String, AnyObject>)

Page 362: Intermediate Swift Language by Apple

Validating a Property List

func stateFromPlist(list: Dictionary<String, AnyObject>) -> State?

Page 363: Intermediate Swift Language by Apple

Validating a Property List

func stateFromPlist(list: Dictionary<String, AnyObject>) -> State?

stateFromPlist(["name": "California", "population": 38_040_000, "abbr": "CA"])

State(name: California, population: 38040000, abbr: CA)

Page 364: Intermediate Swift Language by Apple

Validating a Property List

func stateFromPlist(list: Dictionary<String, AnyObject>) -> State? !

stateFromPlist(["name": "California", "population": "hella peeps", "abbr": "CA"])

Page 365: Intermediate Swift Language by Apple

Validating a Property List

func stateFromPlist(list: Dictionary<String, AnyObject>) -> State? !

stateFromPlist(["name": "California", "population": "hella peeps", "abbr": "CA"])

nil

Page 366: Intermediate Swift Language by Apple

Validating a Property List

func stateFromPlist(list: Dictionary<String, AnyObject>) -> State? !

stateFromPlist(["name": "California", "population": 38_040_000, "abbr": "Cali"])

Page 367: Intermediate Swift Language by Apple

Validating a Property List

func stateFromPlist(list: Dictionary<String, AnyObject>) -> State? !

stateFromPlist(["name": "California", "population": 38_040_000, "abbr": "Cali"])

nil

Page 368: Intermediate Swift Language by Apple

Putting Patterns Together

Page 369: Intermediate Swift Language by Apple

Putting Patterns Together

func stateFromPlist(list: Dictionary<String, AnyObject>) -> State? {

Page 370: Intermediate Swift Language by Apple

Putting Patterns Together

func stateFromPlist(list: Dictionary<String, AnyObject>) -> State? { var name: NSString? switch list["name"] { case

Page 371: Intermediate Swift Language by Apple

Putting Patterns Together

func stateFromPlist(list: Dictionary<String, AnyObject>) -> State? { var name: NSString? switch list["name"] { case .Some( ):

Page 372: Intermediate Swift Language by Apple

Putting Patterns Together

func stateFromPlist(list: Dictionary<String, AnyObject>) -> State? { var name: NSString? switch list["name"] { case .Some( ):as NSString

Page 373: Intermediate Swift Language by Apple

Putting Patterns Together

func stateFromPlist(list: Dictionary<String, AnyObject>) -> State? { var name: NSString? switch list["name"] { case .Some( ):let listName as NSString

Page 374: Intermediate Swift Language by Apple

Putting Patterns Together

func stateFromPlist(list: Dictionary<String, AnyObject>) -> State? { var name: NSString? switch list["name"] { case name = listName

.Some( ):let listName as NSString

Page 375: Intermediate Swift Language by Apple

Putting Patterns Together

func stateFromPlist(list: Dictionary<String, AnyObject>) -> State? { var name: NSString? switch list["name"] { case name = listName default: name = nil }

.Some( ):let listName as NSString

Page 376: Intermediate Swift Language by Apple

func stateFromPlist(list: Dictionary<String, AnyObject>) -> State? { !

switch case

Putting Patterns Together

list["name"] {:

name = listName default: name = nil }

var name: NSString?

.Some( )let listName as NSString

Page 377: Intermediate Swift Language by Apple

func stateFromPlist(list: Dictionary<String, AnyObject>) -> State? { !

switch case

Putting Patterns Together

( , list["population"], list["abbr"])list["name"] {:.Some( )let listName as NSString

Page 378: Intermediate Swift Language by Apple

( , .Some(let pop as NSNumber), .Some(let abbr as NSString))

func stateFromPlist(list: Dictionary<String, AnyObject>) -> State? { !

switch case

Putting Patterns Together

( , list["population"], list["abbr"])list["name"] {.Some( )let listName as NSString

Page 379: Intermediate Swift Language by Apple

( , .Some(let pop as NSNumber), .Some(let abbr as NSString))

func stateFromPlist(list: Dictionary<String, AnyObject>) -> State? { !

switch case

Putting Patterns Together

( , list["population"], list["abbr"])list["name"] {

where abbr.length == 2:

.Some( )let listName as NSString

Page 380: Intermediate Swift Language by Apple

( , .Some(let pop as NSNumber), .Some(let abbr as NSString))

func stateFromPlist(list: Dictionary<String, AnyObject>) -> State? { !

switch case

Putting Patterns Together

( , list["population"], list["abbr"])list["name"] {

where abbr.length == 2: return State(name: listName, population: pop, abbr: abbr)

.Some( )let listName as NSString

Page 381: Intermediate Swift Language by Apple

( , .Some(let pop as NSNumber), .Some(let abbr as NSString))

func stateFromPlist(list: Dictionary<String, AnyObject>) -> State? { !

switch case

Putting Patterns Together

( , list["population"], list["abbr"])list["name"] {

where abbr.length == 2: return State(name: listName, population: pop, abbr: abbr)default: return nil

.Some( )let listName as NSString

Page 382: Intermediate Swift Language by Apple

( , .Some(let pop as NSNumber), .Some(let abbr as NSString))

func stateFromPlist(list: Dictionary<String, AnyObject>) -> State? { !

switch case

Putting Patterns Together

( , list["population"], list["abbr"])list["name"] {

where abbr.length == 2: return State(name: listName, population: pop, abbr: abbr)default: return nil

}}

.Some( )let listName as NSString

Page 383: Intermediate Swift Language by Apple

Pattern Matching

Page 384: Intermediate Swift Language by Apple

Pattern Matching

Tests the structure of values

Page 385: Intermediate Swift Language by Apple

Pattern Matching

Tests the structure of values

Improves readability—Patterns are concise and composable

Page 386: Intermediate Swift Language by Apple

Pattern Matching

Tests the structure of values

Improves readability—Patterns are concise and composable

Improves safety—Variable bindings are tied to the conditions they depend on

Page 387: Intermediate Swift Language by Apple

Swift

Page 388: Intermediate Swift Language by Apple

Swift

Optionals

Page 389: Intermediate Swift Language by Apple

Swift

Optionals

Memory management

Page 390: Intermediate Swift Language by Apple

Swift

Optionals

Memory management

Initialization

Page 391: Intermediate Swift Language by Apple

Swift

Optionals

Memory management

Initialization

Closures

Page 392: Intermediate Swift Language by Apple

Swift

Optionals

Memory management

Initialization

Closures

Pattern matching

Page 393: Intermediate Swift Language by Apple

More Information

Dave DeLong App Frameworks and Developer Tools Evangelist [email protected]

!

Documentation The Swift Programming Language Using Swift with Cocoa and Objective-C http://developer.apple.com

!

Apple Developer Forums http://devforums.apple.com

Page 394: Intermediate Swift Language by Apple

Related Sessions

• Introduction to Swift Presidio Tuesday 2:00PM

• Advanced Swift Presidio Thusday 11:30AM

• Integrating Swift with Objective-C Presidio Wednesday 9:00AM

• Swift Interoperability in Depth Presidio Wednesday 3:15PM

• Swift Playgrounds Presidio Wednesday 11:30AM

• Introduction to LLDB and the Swift REPL Mission Thursday 10:15AM

• Advanced Swift Debugging in LLDB Mission Friday 9:00AM

Page 395: Intermediate Swift Language by Apple

Labs

• Swift Tools Lab A Wednesday 2:00PM

• Swift Tools Lab A Thursday 9:00AM

• Swift Tools Lab A Thursday 2:00PM

• Swift Tools Lab A Friday 9:00AM

• Swift Tools Lab A Friday 2:00PM

Page 396: Intermediate Swift Language by Apple