Chapter    23

if Statements

if statements are used when you want to make a choice to execute code based on the result of a comparison expression. To make this work, you evaluate an expression that uses comparison and logical operators to yield a true or false result. If you evaluate an expression to be true, then you can execute the code; otherwise, you can ignore the code.

You need the if keyword and an expression along with a code block to use the if statement (see Listing 23-1).

Listing 23-1. if Statement

if (1 < 2){    println("This is true")}

The statement is saying that if 1 is less than 2, then execute the code that will print out the string “That is true” to the console log.

else Keyword

You can also define an alternate action with the ...

Get Swift Quick Syntax Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.