FYI on Optionals in Playground

Just thought I would point this out because it took me a few to figure out what was going on.

I had the following in my Playground. I commented out “var reading3: Float?” expecting to see “Instrument reported a reading that was nil.”. I got nothing. I finally figured out that you have to also comment out “let avgReading = (reading1! + reading2! + reading3!) / 3” as this fails therefore anything after that in the playground fails.

//Optionals
var reading1: Float?

var reading2: Float?

var reading3: Float?

reading1 = 9.8

reading2 = 9.2

reading3 = 9.7

//Must Unwrap an optional to use…! unwraps

let avgReading = (reading1! + reading2! + reading3!) / 3

//this is better ways to unwrap

if let r1 = reading1,
let r2 = reading2,
let r3 = reading3
{
let avgReading = (r1 + r2 + r3) / 3
}
else
{
let errorString = “Instrument reported a reading that was nil.”
}

Yes, I noticed that playground behavior also. Apparently, the error-checking and execution starts at the top and works downward line-by-line until it encounters the end or an error.