Swift Optionals Quick Reference for Newbies by Santiapps.com
Swift Optionals Quick Reference for Newbies by Santiapps.com
Swift Optionals Quick Reference for Newbies by Santiapps.com

Optionals confuse me so I wrote this post and hope it can be of some help.

OPTIONALS

Takeaway #1: Optionals are used to declare a variable but are not assigned a value at start

Takeaway #2: Optionals contain a Some or None value, they DONT contain a String or Array or whatever else.

Takeaway #3: Therefore we MUST unwrap the value of an Optional to see what the prize is 🙂 In other words, to access its value!

Takeaway #4: DECLARATION OPTIONS

A) Using the following syntax: var someVar? – You will mostly use this…

B) Using “var someVar!” <Implicitly unwrapped> – Unfortunately UIKit & other Apple frameworks will use a lot of these…

… NEED TO EXPLORE THE DIFFERENCE BETWEEN ? and ! declarations…

Turns out you can declare a variable as an implicitly unwrapped optional if you know it will, at some point, be non-nil.  So for example, in this SO post (http://stackoverflow.com/questions/24006975/why-create-implicitly-unwrapped-optionals) they talk about have viewDidLoad in a view controller call a setter upon load:

var screenSize: CGSize?

override func viewDidLoad() {

super.viewDidLoad()

screenSize = view.frame.size

}

We know that screenSize will be filled because viewDidLoad WILL be called.  Then later we do:

@IBAction printSize(sender: UIButton) {

println(“Screen size is: \(screenSize!)”)

}

We know screenSize will have a value if its ever called.  So we can instead declare it as an implicitly unwrapped optional with a ! instead of a ? in the initial var declaration.  But don’t sweat this so much right now.

Takeaway #5: ACCESS (UNWRAPPING) OPTIONS 

Takeaway #6: Method 1: Traditional (Risky): if var != nil and then access it inside the if block.

if yourOptionalTypeOrOptionalReturningFunction != nil {

doSomethingWith(tempOptional!) || setSomeValue = tempOptional!

}

But to access it you have to unwrap the present 🙂  To do this you use the bang operator !  Whenever you use the ! you are ‘force unwrapping’ a variable, which means it will open it no matter what.  If nil is in there…KABOOM!  Bye bye Moose & Squirrel!  So you better have checked before hand.

Takeaway #7: Method 2: Optional Binding (aka:”if-let nil check”) (Safer): This means you use:

if let tempOptional = yourOptionalTypeOrOptionalReturningFunction {

doSomethingWith(tempOptional) || setSomeValue = tempOptional

}

This is more safe because it checks first or peeks in the box so to speak.  Thus you can use the variable without unwrapping.

< If you remove default value from a ? and have a ! to access it in code, your code will fail if-check will go to else.>

Takeaway #7: Method 3: Implicitly Unwrap: Uses ! operator (assumes var contains some value). But remember from Method 1, if nil, KABOOM!!!!!!

<If you remove default value from a ? and have a ! to access it in code, you get runtime crash = error = “can’t unwrap optional.None”>

Takeaway #8: Optionals unwrapped using? – This one is still kinda confusing to me. Has to do with optional chaining and inline downcast syntax I believe.  It means that when you have many optionals.  Let’s assume you have a class with 2 optional variables, name? and price?  Let’s pretend you write a function that creates a new Stock() class object and must therefore set name & price variables for it.  We would first have to check if one is set and then the other:

if let someName = stock.name {

if let somePrice = stock.price {

//now we can do something with price…

}

}

This would get messy.  So we chain them into a single statement like so:

someVariableWeWantToSet = stockName?.stockPrice

Takeaway #10: Many ObjC framework objects are optionals? and many are implicitly unwrapped! when passed into functions because they will start out as nil (UILabels, MKAnnotationViews or MKPolylines) but we know they will eventually get filled in because that’s why we put them there in the first place:

MKAnnotationView!

MKAnnotation!

UIControl!

MKPinAnnotationView!

MKMapView!

Takeaway #11: When we have something like an MKAnnotation! is received in a function as annotation. If we wish to use its super class properties, we must be inline downcast to while if-let checking. Once inside we can implicitly (force) unwrap MKPinAnnotationView! because we know since the annotation exists, it will have a view. For example, in this method:

func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {

if let polylineOverlay = overlay as? MKPolyline {

let renderer = MKPolylineRenderer(polyline: polylineOverlay) renderer.strokeColor = UIColor.blueColor()

return renderer

}

return nil

}

We can interpret that funky as? as follows: “If when I get the variable overlay and unwrap it, it downcasts successfully to a MKPolyline && I get a value (not-nil) then put it into polylineOverlay & continue…” Hope this helps…

One Comment

Leave a Reply