I am just transitioning from Objective-C to Swift and have been constantly writing the following code for optional binding,
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? 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
Xwill only be visible inside theifscope.But if you use a
guardstatement, the newXmay shadow the previous variable (i.e., if previous variable was defined in another scope; otherwise will trigger a compiler error). Some would say this could hurt your code readability.For further information, please see this related question.