search by tags

for the user

adventures into the land of the command line

declaring variables in swift 2

Swift is a strongly and statically typed language. That means you have to declare variables before you can initialise them, and you have to explicitly mention what data type the variable or constant is going to store.

A constant is an immutable value and you declare it like this:

let something:String!

A variable is an mutable value and you declare it like this:

var something:String?

The exclamation mark ’!’ means that this variable must not be empty when it is used. The question mark ’?’ means that this variable may be empty when it is used.

You can make variables available globally:

public var something:String?

Or to the class that encapsulates it:

private var something:String?

or just simply

var something:String?

You initialise variables by putting something into them. You don’t have to declare the datatype if you initialise the variable to something right away:

var something = "String"

Although you can:

var something:String = "String"

Here’s a bunch of data structures:

STRING ->     var something:String = ""
ARRAY ->      var something = [NSTimeInterval]()
ARRAY ->      var something:[String!] = []
DICTIONARY -> var something = [String:Int]()
DICTIONARY -> var something:Dictionary
TUPLE ->      var something = (String,Int)

A tuple containing an array of tuples containing a dictionary ->
var something = (Double(),[(String,Dictionary)]())

An array containing a tuple containing an array of tuples containing a dictionary ->
var something = [ (Double(), [ (String,Dictionary) ]() ) ]