On page 36, I get the error message (Initialization of immutable value was never used…) on this part of the code:
{ let avgReading = (r1 + r2 + r3)/3 }
else
{ let errorString = “Instrument reported a reading that is nil.”}
In order to get my code to work I had to use an underscore, below is the code that works:
var reading1: Float? = 9.8
var reading2: Float? = 9.2
var reading3: Float? = 9.7
//Optional Binding, unwrapping with if-let (P36)
if let r1 = reading1,
let r2 = reading2,
let r3 = reading3
{ _ = (r1 + r2 + r3)/3 }
else
{ _ = “Instrument reported a reading that is nil.”}
Those are just warnings. Technically, they’re correct - you’re defining avgReading and errorString within an if/then/else statement and never using them for anything. The compiler is just giving you a heads up that you may have made a mistake (since you normally wouldn’t do that). But in this case, you’re just playing around with the optional bindings, and those two variables are just there so you have something inside the braces, so the fact that they’re unused isn’t an issue.
Thanks. I find the code readability of the _ (underscore) a little harder than using a variable, even if the variable is not being used for anything. The compiler is telling me that I initialized a variable and never used it, but it seems like I am using it when I assign the value to it, I think???
Well, technically, yes you’re “using” a variable when you assign a value to it, but that’s only useful if you subsequently read the value back out again, otherwise why did you bother? When the compiler sees a variable created & then never used again, it thinks one of three things probably happened:
-
You forgot to add the code that would use the variable for something.
-
You made a typo, and the variable name is incorrect and should be something else.
-
You deleted the code that used the variable & accidentally left behind the code that created it when you meant to delete it also.
But the compiler isn’t smart enough to know which one of those is actually the case, so all it can do is draw your attention to it.
Lol, too funny, made my day.