为什么不重新声明“可选绑定”会创建错误? [英] Why DOESN'T redeclaration of 'optional binding' create an error?

查看:117
本文介绍了为什么不重新声明“可选绑定”会创建错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Playground做这个,但我没有得到任何错误。我不重新创建常量 range ?它发生在两个不同的范围?在背景中发生了什么使这个不是错误?

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


推荐答案

使用 if-let 的可选绑定引入的变量在 let - 直到真实代码块结束。

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 是另一回事。)

这篇关于为什么不重新声明“可选绑定”会创建错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆