简体   繁体   English

带常量和作用域的Swift可选绑定

[英]Swift Optional Binding with Constants, and Scope

I'm trying to understand why the following is valid in Swift. 我试图理解为什么以下内容在Swift中有效。 I'm assuming it has to do with the way things are scoped in Swift. 我假设它与Swift中的作用域有关。

let name = "test" //assigns "test" to name
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName { //assigns "John Appleseed" to name
  let name = "no error" //assigns "no error" to name
  greeting = "Hello, \(name)" //assigns "Hello, no error" to greeting
}
println(name) //prints "test"

What I believe is happening is this is creating 3 separate name constants all in different scopes. 我相信正在发生的事情是在不同范围内创建3个单独的名称常量。 The first let name is in the global scope. 第一个let名称在全局范围内。 Then the optional binding let name is another scope, and then within the if the let name is another scope. 然后,可选的绑定let名称是另一个作用域,如果let名称是另一个作用域,则在该范围之内。 Then the final print goes back out to the global scope. 然后,最终打印返回到全局范围。

您已经了解:)它使用找到的第一个具有该名称的变量,从内部范围开始向上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM