Iverson brackets and SwiftUI modifiers
21 Mar 2021 ⇐ 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 Int
1.
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:)
,
someView
.rotationEffect(.degrees(isRotated ? 90 : 0))
// which expands out to,
someView
.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.
-
Or, a
BinaryInteger
conformance for the nerds. ↩ -
Harlan posted a thread on why this approach is preferred over
if
-else
ing inViewBuilder
s.The way to better express this is to create modifiers that take in values to determine how their effects get applied. Nearly every SwiftUI modifier takes in a value, so you can conditionalize it.
— Harlan Haskins (@harlanhaskins) October 29, 2020