简体   繁体   English

Swift可选绑定常量名称

[英]Swift optional binding constant names

I am just transitioning from Objective-C to Swift and have been constantly writing the following code for optional binding, 我只是从Objective-C过渡到Swift,并一直在编写以下代码进行可选绑定,

if let tempX = X {

}

My question is I have to do it so often that I need to find a new name for constant every time. 我的问题是我必须经常这样做,以至于每次都需要为常量查找一个新名称。 What's the way to avoid having a new name tempX for every optional X in the code? 如何避免对代码中的每个可选X使用新名称tempX? Wouldn't something like work? 会不会像工作?

if let X = X {

}

Yes, you can reuse the same identifier in such bindings. 是的,您可以在此类绑定中重复使用相同的标识符。 But keep in mind that the redefined, non-optional X will only be visible inside the if scope. 但是请记住,重新定义的非可选X仅在if范围内可见。

But if you use a guard statement, the new X may shadow the previous variable (ie, if previous variable was defined in another scope; otherwise will trigger a compiler error). 但是,如果使用guard语句,则新的X可能会覆盖先前的变量(即,如果先前的变量是在另一个作用域中定义的,否则将触发编译器错误)。 Some would say this could hurt your code readability. 有人会说这可能会损害代码的可读性。

For further information, please see this related question . 有关更多信息,请参见此相关问题

The new constant is only defined within the scope of your if let, so as soon as the scope is over, your tempX is gone. 新常量只在if let的范围内定义,因此一旦范围结束,tempX就会消失。 That also means that you can reuse names within the if let scope. 这也意味着您可以在if let范围内重用名称。

if let X = X {

}

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

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