Codecademy Logo

Variables

Print Cheatsheet

Variables

A variable refers to a storage location in the computer’s memory that one can set aside to save, retrieve, and manipulate data.

var score = 0

Constants

Constants refer to fixed values that a program may not alter during its execution. One can be declared by using the let keyword.

let pi = 3.14

Arithmetic Operators

Swift supports arithmetic operators for:

  • + addition
  • - subtraction
  • * multiplication
  • / division
  • % remainder
var x = 0 x = 4 + 2 // x is now 6 x = 4 - 2 // x is now 2 x = 4 * 2 // x is now 8 x = 4 / 2 // x is now 2 x = 4 % 2 // x is now 0

Types

Type annotation can be used during declaration.

The basic data types are:

  • Int: integer numbers
  • Double: floating-point numbers
  • String: a sequence of characters
  • Bool: truth values
var age: Int = 28 var price: Double = 8.99 var message: String = "good nite" var lateToWork: Bool = true

String Interpolation

String interpolation can be used to construct a String from a mix of variables, constants, and others by including their values inside a string literal.

var apples = 6 print("I have \(apples) apples!") // Prints: I have 6 apples!

Compound Assignment Operators

Compound assignment operators provide a shorthand method for updating the value of a variable:

  • += add and assign the sum
  • -= subtract and assign the difference
  • *= multiply and assign the product
  • /= divide and assign the quotient
  • %= divide and assign the remainder
var numberOfDogs = 100 numberOfDogs += 1 print("There are \(numberOfDogs) dalmations!") // Prints: There are 101 dalmations!