Apple\'s Swift language documentation says that optional binding (a.k.a. if let
) will \"check for a value inside an optional\" and \"extra
I interpret this 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 for checking if an optional contains a value to pass to a non optional parameter.
You assigned an optional Int to an optional Int. The assignment did succeed. It will always succeed, whether the optional Int contained an Int or not.