Skip to content

Instantly share code, notes, and snippets.

@loganwright
Last active August 29, 2015 14:02
Show Gist options
  • Save loganwright/ee7f62d5cc95df32ef07 to your computer and use it in GitHub Desktop.
Save loganwright/ee7f62d5cc95df32ef07 to your computer and use it in GitHub Desktop.
import Cocoa
// LET vs. VAR
/* Up to this point, we have declared all of our names using the keyword `var`. Swift however makes use of another type of variable declaration with the keyword 'let'. At its most basic, `let` indicates that something is constant and `var` indicates that something is variable. */
/* In the following code, we will create a new constant named `someConstant` that will be an unchanging value */
let someConstant = "I am forever constant"
/* This means that someConstant can no longer be modified. The following code will show an error: "Cannot assign to 'let' value"*/
// Error
// someConstant = "Let's modify it"
/* It's important to note that this means that the location of the object in memory is constant, but the values within that memory can possibly be modified. Let's take the following example with a familiar cocoa object ... the dreaded NSDateFormatter */
let formatter = NSDateFormatter()
formatter.locale = NSLocale.currentLocale()
formatter.dateFormat = "MM/dd/yyyy"
/* You'll notice that I can set the properties of this object without modifying the 'formatter' name. If I try to modify the address of 'formatter' I will run into problems. For example, the following code won't work */
var newFormatter = NSDateFormatter()
// ERROR
// formatter = newFormatter
/* If the same name will be assigned to different values, you should declare it as variable using 'var' */
/* *** APPLE NOTE ***
If a stored value in your code is not going to change, always declare it as a constant with the let keyword. Use variables only for storing values that need to be able to change.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment