Variables and if statements

To create a new playground, launch XCode, and select:

File -> New -> Playground...

There are two types of comments:

  • A comment that uses two slashes ( // ). Everything to the right of the slashes is ignored by the compiler.
  • A comment that starts with /* and ends with */. Everything between these two markings is a comment - even if it's across multiple lines.


var name = "Tim" // This is a comment, but it ends at the end of the line.
/* This comment
goes across
multiple lines */

Like the name implies, a variable can hold a value, but that value can change over time. Some variables are numbers, while others are strings.

// This is a variable equal to 5
var x = 5

// This is a new variable named 'y', and it has a value of x + 5 (or 10, in this case)
var y = x + 5

// This is a string of characters (or, letters)
var salutation = "Hello, my friend!"

// This line of code concatenates the original salutation, and another string. The result is the combination of the two strings
salutation = salutation + " It's good to see you!"

// This prints Hello, my friend! It's good to see you! to the console.

The if Statement
It's possible to create conditional logic by including an if statement. The basic structure is as follows:

var someNumber = 5
if someNumber > 4 {
  print("Five or greater")
} else {
  print("Four or less")

In the above example, a variable is checked to see if it has a numeric value greater than four. If so, then Five or greater is printed to the console. If the value is not greater than four, then Four or less is printed to the console.