Why doesn't redeclaration of 'optional bin

2019-09-18 16:56发布

问题:

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

回答1:

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