Boolean And/Or

In Shim there are logical operators and and or. The basic behavior of these operators follows standard boolean logic.

print("false and false =", false and false)
print("false and true =", false and true)
print("true and false =", true and false)
print("true and true =", true and true)

print("false or false =", false or false)
print("false or true =", false or true)
print("true or false =", true or false)
print("true or true =", true or true)
Press the play button to execute

Or Short-Circuiting

Like Python these operators have a bit more to them. The or operator doesn’t just return true if both sides are truthy. Instead, Shim evaluates the left operand. If that operand is truthy, then the value returned by or is that left operand. The right expression never gets evaluated. If it’s falsy, the value returned by or is the right operand.

This behavior for or is a common way to assign a default value. Here is an example not using or:

let name = None
name = if name { name } else { "Kate" }
print("Hello, \(name)")
Press the play button to execute
let name = None
name = name or "Kate"
print("Hello, \(name)")
Press the play button to execute

Since the right operand is only evaluated if the left side is not truthy, then code like this will not panic. This is called “short-circuiting”.

print(4 or panic("Would fail if evaluated"))
Press the play button to execute

And Short-Circuiting

The and operator is complementary to the or operator. The and operator returns the left operand if it’s falsy, otherwise it returns the right operand.

print("0 and 42 =", 0 and 42)
print("1 and 42 =", 1 and 42)
Press the play button to execute

If the left operand is falsy, the expression for the right operand never evaluates. This lets you write predicates like this:

let lst = []
if lst and lst[0] == "foo" {
    print("First element of list is foo")
}
Press the play button to execute

If Shim did evaluate the expression for the right operand then it would cause an error.