Why does the optional Swift binding succeed with "nil" in certain cases?

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

+2
if-statement swift optional
source share
2 answers

I interpret it differently:

 var x: Int? = 1 if let y1: Int = x { println("y1 = \(y1)") } //prints y = 1, the optional was checked, contains a value and passes it var x: Int? = nil if let y1: Int = x { println("y1 = \(y1)") } //does not execute because x does not contain value that can be passed to a non optional y var x: Int? = nil if let y1: Int? = x { println("y1 = \(y1)") } // y = nil, since y is optional and can hold a value of x which is nil, then it passes nil 

Optional binding is intended to check if the optional value has a value for the optional parameter.

+2
source share

You have assigned an additional Int to an additional Int. The assignment was successful. It will always be successful, whether it's an extra Int containing Int or not.

+1
source share

All Articles