0

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 {

}
Deepak Sharma
  • 5,577
  • 7
  • 55
  • 131

2 Answers2

2

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.

Community
  • 1
  • 1
Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
1

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 {

}