I’m reviewing code as I prepare to remove postfix decrements in Swift 3.0. Here’s an example and a story.
Before my review, I had a postfix decrement on line 22, the one with the
This approach is conventional, or at least C-conventional because it is no longer going to be allowed in Swift. The decrement takes place after the random number generation, ensuring that the random number falls between
endBoundary - 1. After the call,
endBoundary is decremented and the math that follows takes place with respect to that decremented
At first, I toyed with scenarios for tweaking the
endBoundary update. My gut told me to keep the boundary math close to the original location. I tried adding it to the same line with a semi-colon. Then I placed it on the next line. I considered using a defer statement and adjusting the math for the swap.
It wasn’t until I started properly adding comments that it became clear in the algorithm story where the
endBoundary adjustment belonged. Until commenting, I’d been acting reflexively: I decremented the boundary count after rolling the dice because that is how I had always done it in C. But the boundary didn’t really affect my math until the swap. While I initially thought the update belonged before the
nextIndex assignment, adding comments showed it fit better after.
This is a case of “but I did it this way in C, so it should work this way in Swift”. I was bemused when I first read the proposed language evolution change. Now that I’m trying to apply the change to my code, it’s making me see things in a new light.