Iverson brackets and SwiftUI modifiers

⇐ Notes archive

(This is an entry in my technical notebook. There will likely be typos, mistakes, or wider logical leaps — the intent here is to “let others look over my shoulder while I figure things out.”)

I love noticing when an everyday engineering practice has a named analog in mathematics. This time around, it was Iverson brackets. The Wikipedia page is…a lot, so no frets if it’s intimidating — the non-mathematician’s reading of it is the expression $[P]$ is equal to $1$ if $P$ is true or $0$, if false, where $P$ is some predicatetrue-false statement.

In Swift speak, a function from Bool to Int1.

In SwiftUI speak, conditionally setting a modifier’s value2. Most commonly with opacity(_:),

someView.opacity(isShown ? 1 : 0).

And implicitly with others like rotationEffect(_:anchor:),

  .rotationEffect(.degrees(isRotated ? 90 : 0))

// which expands out to,

  .rotationEffect(.degrees(90 * (isRotated ? 1 : 0)))

The isShown ? 1 : 0 and isRotated ? 1 : 0 ternaries are Iverson brackets in disguise. Kinda nifty to see another domain’s language around this type of expression. I came across the notation in an answer to the question of “What is the sum of number of digits of the numbers $2^{2001}$ and $5^{2001}$?” asked over on Math Stack Exchange.

The next note will likely pencil in the intermediary steps of that solution.

  1. Or, a BinaryInteger conformance for the nerds. 

  2. Harlan posted a thread on why this approach is preferred over if-elseing in ViewBuilders.