The Sway Reference Manual/Conditionals

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Conditionals implement decision points in a computer program. Suppose you have a program that performs some task on an image. You may well have a point in the program where you doe one thing if the image is a JPEG and quite another thing if the image is a GIF file. Likely, at this point, your program will include a conditional expression to make this decision.

Before learning about conditionals, it is important to learn about logical expressions. Such expressions are the core of conditionals and loops[1].

Logical expressions[edit | edit source]

A logical expression evaluates to a truth value, in essence true or false. For example, the expression x > 0 resolves to true if x is positive and false if x is negative or zero. In Sway, truth is represented by the symbol :true and falsehood by the symbol :false. Together, these two symbols are known as Boolean values.

One can assign truth values to variables:

     var z = c > 0;

Here, the variable z has a value of :true if c is positive; otherwise it has a value of :false.

Logical operators[edit | edit source]

Sway has the following logical operators.

   ==  equal to
   >=  greater than or equal to
   >   greater than
   <=  less than or equal to
   !=  not equal to
   &&  and
   ||  or

The first five operators are used for comparing two things, while the last two operators are the glue that joins up simpler logical expressions into more complex ones.

Short circuiting[edit | edit source]

When evaluating a logical expression, Sway evaluates the expression from left to right and stops evaluating as soon as it finds out that the expression is definitely true or definitely false. For example, when encountering the expression

     x != 0 && y/x > 2

if x has a value of 0, the subexpression on the left side of the && connective resolves to false. At this point, there is no way for the entire expression to be true (since both the left hand side and the right hand side must be true for an && expression to be true), so the right hand side of the expression is not evaluated. Note that this expression protects against a divide-by-zero error.

There are two basic constructs for selecting among alternatives in Sway. They are the if-then-else statement and the switch (or case) statement.

If expressions[edit | edit source]

Sway's if expressions are used to conditionally execute code, depending on the truth value of what is known as the test expression. One version of if has a block of code following the test expression:

Here is an example:

   if (name == "John")
       println("What a great name you have!");

In this version, if the test expression is true (i.e., the string "John" is bound to the variable name), then the following block is executed (i.e., the compliment is printed). If the test expression is false, the following block is not executed.

Unlike most programming languages, Sway's if is a function. In the above example, the two arguments are the test expression and the following block. The following block is known as a proximal block.

Here is another form of if:

   if (major == "Computer Science")
       println("Smart choice!");
       println("Ever think about changing your major?");

In this version, if takes three arguments: the test expression and the two following blocks[2]. As before, the first block is evaluated if the test expression is true. If the test expression is false, however, the second block is evaluated instead.

Be aware that any proximal arguments must be blocks. Although the following is legal in some languages, a syntax error will be generated in Sway:

   if (name == "John")
       println("What a great name you have!"); //not a block!

Since wrapping a single expression in a block can be considered tedious, you may dispense with the proximal blocks and use regular function call syntax for if:

   if (a < b,min = a,min = b);   //find the minimum of two numbers

The above is equivalent to:

   if (a < b)
       min = a;
       min = b;

Note that if you move expressions inside as regular arguments, you will need a semicolon after the close parenthesis, as with any other function call.

The function if has a return value, as does any other function in Sway. Indeed, you can use the return value to simplify the above expression:

   min = if (a < b) { a; } else { b; };


   min = if (a < b,a,b);

If you use the return value of an if, you must end the expression with a semicolon, regardless of whether you use proximal blocks or not.

Remember, if you use an if by itself and the if has proximal blocks, do not follow the expression with a semicolon. Otherwise a semicolon is needed at the end of the entire expression containing the if.

if chains[edit | edit source]

You can chain if expressions together, as in:

   if (bases == 4) { println("HOME RUN!!!"); }
   else if (bases == 3) { println("Triple!!"); }
   else if (bases == 2) { println("double!"); }
   else if (bases == 1) { println("single"); }
   else { println("out"); }

As before, the value of the block that is eventually evaluated is the return value of the entire construct. If no block is evaluated, the return value is :false.

What is the difference between chained ifs and a sequence of unchained ifs? For example,

   if (bases == 4) { println("HOME RUN!!!"); }
   if (bases == 3) { println("Triple!!"); }
   if (bases == 2) { println("double!"); }
   if (bases == 1) { println("single"); }
   else { println("out"); }

The answer is left as an exercise for the reader.

Switch expressions[edit | edit source]

The above if-chain can be rewritten using a switch expression:

  var x = 0;
  switch (x)
      case(4) { println(x,"HOME RUN!!!"); }
      case(3) { println("Triple!!"); }
      case(2) { println("double!"); }
      case(1) { println("single"); }
      else    { println("out"); }

If the switch expression, in this case x, matches any of the case expressions, in this case 4, 3, 2, and 1, then the block following the matching case is evaluated.

In languages like C, the switch statement is more efficient than an equivalent if-chain. In Sway, not so much. In fact, the switch is equivalently (un)-efficient, but often more pleasing to the eye. Unlike C, which requires the switch and case expressions to be integral and known at compile time, Sway's switch is much more flexible, in that both kinds of expressions can be any valid Sway expression, including variables.

To use switch, you will need to include the basics library. To use the "basics" library, add the function call:


at the top of your source code file.

As with if, switch is a function with proximal block arguments. By itself, a call to switch with a proximal block does not have a terminating semicolon As with if, switch is a function with proximal block arguments. By itself, a call to switch with a proximal block does not have a terminating semicolon. In all other cases, s semicolon will be needed.

Footnotes[edit | edit source]

  1. We will learn about loops in the next chapter.
  2. The else is there for looks only and is known as 'syntactic sugar'.

Debugging · Loops