Contact Us

Use the form on the right to contact us.

You can edit the text in this area, and change where the contact form on the right submits to, by entering edit mode using the modes on the bottom right. 


Oak Ridge, TN, 37830
United States

Variables & Constants

Swift-Snips

Variables & Constants

Wade Cantley

Create a Variable

Pattern

var variableName = value
let variableName = value

Example

var handHeldFood = "Pizza"      // this is a string
var numberOfServings = 1.2  // this is a double
var numberOfForks = 1       // this is an integer 
let bestHeldFood = "Nugget" // this is a constant string

Note : A “var” can be changed later where as a “let” can’t.

Think of it as “let” is like write a variable with a pen. What you write can’t be changed.
“var” variables on the other hand are like writing in pencil. You can use the same paper to write and erase values over and over.

If you code “let it rain!” there is no bringing out the sun again!

! No mathematical symbols in the variable name.
! Don’t start a variable name with a number.

The variable type is determined or “inferred” by the value. You can be explicit but you don’t have to be and the remainder of this guide will leverage Swift’s inferred type systems.

Swift will always infer a type of Double over Float.


Edit a Variable

Pattern

variableName = value

Example

var handHeldFood = "Pizza"  // This sets the variable 
handHeldFood = "toast"      // this changes the variable 

Copy a Variable

Pattern

var variableName = otherVariableName

Example

var handHeldFood = "Pizza"      // This is “Pizza” 
var triangleFood = handHeldFood     // Now this is “Pizza” too

triangleFood = "nacho chip"     // Change to “nacho chip”

triangleFood                    // this is “nacho chip” 
handHeldFood                    // this is still “Pizza”

Note : Why is this important?

Copying variables used to just simply copy a reference to the same value. That means two different names for the same value. The problem is that when you change the value of one, it changed it for the original. In swift, every different variable is independent. So copying a variable into another variable is just that.. a copy of the original.