Skip to content

Instantly share code, notes, and snippets.

@loganwright
Created June 3, 2014 17:22
Show Gist options
  • Save loganwright/ace6d522ead988e64449 to your computer and use it in GitHub Desktop.
Save loganwright/ace6d522ead988e64449 to your computer and use it in GitHub Desktop.
import Cocoa
/* To declare a variable in Swift, simply assign something to it, like below: */
var str = "Hello, playground"
/* As you can see, there is no explicit type declared. This is because type inference will notice that the variable 'str' is being assigned a string and the compiler will infer that str is of type 'String' */
/* You can declare a Type explicitly using a 'Type Annotation' like this */
var strVar: String = "Something"
/* The colon can be read as `of type` so this code would read "variable strVar of type String equals "Something" */
/* It is rare that you will need type annotations in practice if you provide an initial value for a variable. This is because the compiler will be able to infer the type (as discussed earlier). If however, you are declaring a variable before defining it, it might be useful to declare it ahead of time. Consider this */
var someMessage: String
/* At this point, the compiler knows that someMessage will be a string even before it has been assigned. If we try to assign a value other than a string, it will show an error. */
// OK
someMessage = "Hello!"
// Error
// someMessage = 15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment