Swift Swap

I often come across conditions where initial and final values are exchanged depending upon a boolean flag. For example:

func showSomeView(show: Bool) {
var initialTransform = // center of screen
var finalTransform = // off screen

if show {
initialTransform = // offscreen
finalTransform = // center of screen
}

// perform animation
}

This is pretty clunky. There are other ways of doing the same thing using let to declare variables and then switch/if-else to assign values to the variables. However, this leads to some tough to read code. But there is an alternate way which leads to very declarative code. It’s using the (undocumented?) swap function:

func showSomeView(show: Bool) {
var initialTransform = // center of screen
var finalTransform = // off screen
    if show { swap(&showTransform, &hideTransform) }

// perform animation
}

If you find the & odd, it means that the function takes inout parameters. This allows passing values by reference to the swap function which then modifies them. As is obvious, the initialTransform and finalTransform variables have to be declared as vars and not lets.

This was originally posted on my own site.