Honey Honey - 3 months ago 9
Swift Question

Why DOESN'T redeclaration of 'optional binding' create an error?

I am doing this in Playground, but I am not getting any error. Am I not recreating constant

range
? Is it happening in 2 different scopes? What's happening in the background that makes this not an error?

if let range = add1.rangeOfString(", ") {
print(add1.substringToIndex(range.startIndex))
print (range)
}

if let range = add1.rangeOfString(", ") {
print(add1.substringToIndex(range.startIndex))
print (range)
}

Answer

Variables introduced with Optional binding of if-let is local after the let-clause till the end of true-case code block.

So, yes. Your two range reside in 2 different scopes.

(guard-let is another thing.)

Comments