Intermediate SWIFT

Optionals    //safer

Memory management    // large automatic

Initialization

Closures

Pattern matching

 

optionals

let age = response.toInt()

optional Type    represents possibly missing values

var optionalNumber: Int?    //default initialized to nil

non-optional Types    // can’t be nil

var myString: String = “hello”

Optional return Types

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

if value = string {

return value

}

return nil

}

Optional Binding(!)

test and unwrap at the same time

if let indexValue = index {}     // index value is of type int

class Person {

var residence: Residence?

}

class Residence {

var address: Address?

}

class Address {

var buildingNumber: String?

var streetName: String?

var apartmentNumber: String?

}

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

}

optional Chaining(?)

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

                                    CHECK INT or NIL

optionals under the Hood

enum

Memory Management

ARC(Automatic Reference Counting)

predictable

Ownership

class Apartment {

weak var tenant: Person?

}

class Person {

weak var home:Apartment?

func moveIn(apt:Apartment) {

self.home =apt

self.tenant = self

}

}

var renters = [“e”:Person()]

var apts = [5: Apartment()]

renters[“e”]!.moveIn(apts[5]!)

Weak references are optional values

Binding the optional produces a strong reference

Same-Lifetime relationships

class person {

var card: creditCard?

}

class CreditCard {

    weak var holder: person?     // var mutable

//or use unowned holder:person

init(holder:person) {

self.holder = holder

}

}

using unowned references  // like strong,

strong, weak and unowned // among independent lifetime

// back up to their owner

Automatic safe predictable

think about relationship

Initialization (must be initialized)

var message: String

if sessionStarted {

message = “Welcome”

}

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

we need to set else {

message = “see you next year”

}

Initializers (handle responsibility of fully initializing an instance)

init() {…}/init(luckyNumber: Int, message:String){…}

let instance = MyClass()/MyClass(luckyNumber:42, message:”Not day”)

structure Init

struct Color {

let red, green, blue: Double

mutating func validateColor(){…}

init (grayScale:Double){

red = grayScale    // every property must be initialized

green = grayScale

blue = grayScale

self.validateColor()    // must use after set all properties

}

}

Default Value : let red = 0.0, green = 0.0

Class Initialization(self, and superclass[turbo = turbo super.init(color:color)])

class car {

var paintColor: color

func fillGasTank(){…}

init(color:Color) {

paintColor = color

fillGasTank()    // due to override in sub class

}

}

class ReceCar: Car {

var hasTurbo: Bool

override func fillGasTank(){…}

init (color: Color, turBo:Bool) {

hasTurbo = turbo

super.init(color: color)   // must behind hasTurbo.

}

}

Initializer delegation

Convenience Initializers

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

}

Initializer Inheritance

class FormulaOne: RaceCar {

let minmumWeight = 642

// inherit init(color) & init()

}

Lazy properties

class Game {

@lazy var multiplayManger = MultiplayerManager()  // only one time

}

De-initialization

class FileHandle {

let fileDescriptor: FileDescriptor

init(path: String) {

fileDescriptor = openFile(path)

}

deinit {

closeFile(fileDescriptor)

}

}

// set all stored properties first then call super.init

// designated initializers only delegate up

// convenience initializers only delegate across

// de=initializers are there … if you need them

Closures

var clients = [“a”,”b”,”c”]

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

return a<b

})

clients.sort({a,b in a<b})  // type , implicit return

clients.sort({$0<$1}) // implicit arguments

clients.sort($0<$1) // trailing closures

println(words.filter{$0.hasSuffix(“gry”)})  //angry, hungry

                    .map{$0.uppercaseString})  //ANGRY, HUNGRY

                    .reduce(“HULK”) {“\($0) \($1)”})  // HULK ANGRY HUNGRY

Captures

func sum(numbers:Int[]){

numbers.map{sum+=$0}

}

Ownership of captures

class tempNotifier {

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

var currentTemp = 72

init() {

//unowned let uSelf = self

onChange = {[unowned self] temp in

self.currentTemp = temp

}

}

}

Pattern Matching

switch trainStatus {

case .OnTime:

case .delay(1): /.delay(2…10): / .delay(_):

}

enum VacationStatus {

case Traveling(TrainStatus)

case Relaxing(daysLeft: Int)

}

switch vacationStatus {

case .Traveling(.OnTime):

case .Traveling(.Delay(1…5)):

case.Traveling(.Delay(_)):

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s