Apple's quick language documentation says that an optional binding (aka if let ) will “check the value inside the optional” and “extract that value to“ variable or constant. ”But that doesn't match what I see. For example
var x: Int? = nil if let y1: Int? = x { println("y1 = \(y1)") // This is printed, suggesting that x is not checked "inside", but left as Optional(nil) (!= nil) } if let y2: Int? = x? { println("y2 = \(y2)") } if let y3: Int = x? { println("y3 = \(y3)") } if let y4: Int = x { println("y4 = \(y4)") } if let y5 = x? { println("y5 = \(y5)") } if let y6 = x { println("y6 = \(y6)") }
results in (only)
"y1 = nil"
assuming that the check "inside" x occurs in the case y1 (and that x remains in the form of a wrapped nil , which is not equal to the nil ). The y2 case seems to confirm this by forcing a “check inside” (or is it just an optional “capture” chain); but the story should be larger, since the cases y4 and y6 also not printed and thus behave as if there is a “check inside”.
I suspect there is an opportunity to understand that you are trying
"x = 42"
that leads to
"y1 = Optional(42)" "y2 = Optional(42)" "y3 = 42" "y4 = 42" "y5 = 42" "y6 = 42"
but if there are three people, it lost me.
It appears that (1) the “optional” on the right side of the expression is indeed “checked internally” if an explicit check is requested (c ? ); but otherwise (2) the left side of the expression affects how the “inside” of the check is performed (far enough to make a valid assignment).
How does optional binding work in each of these cases? In particular, when x == nil why y1 prints, and given that this is so, why not y4 and y6 (or create assignment errors)?
if-statement swift optional
orome
source share