Swift optional binding constant names

118 Views Asked by At

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 {

}
2

There are 2 best solutions below

2
Paulo Mattos On

Yes, you can reuse the same identifier in such bindings. But keep in mind that the redefined, non-optionalX will only be visible inside the if scope.

But if you use a guard statement, the new X may 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.

0
Steffen Lund Andersen On

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. That also means that you can reuse names within the if let scope.

if let X = X {

}