Swift Tutorial II

Ok so in the first tutorial we covered let, which is the keyword for defining constants.

let thisBeAConstant = 3.141

Now we are going to cover variables, which use the var keyword like so:

var thisVariable = time

Notice 2 things about Swift:

1) We don’t use ; at the end of a line. ¬†That’s just weird ūüôā

2) We don’t have to specify the type. ¬†The type is inferred by whatever value you pass in, so:

var someString = “this is a string”

var someInteger = 5

So Swift is kinda smart. ¬†Now let’s meet some old friends “Hao jiu bu juan”

ARRAYS

var¬†energies = [“solar”,¬†“wind”,¬†“fossil”, “this is a mixed array”,¬†39]

var¬†energies:String[]¬†= [“solar”,¬†“wind”,¬†“this is a string array”]

And of course we can perform some basic operations such as:

READ

var¬†item1 =¬†energies[0] ¬† //¬†“solar”

INSERT

energies.insert(“hydro”, atIndex: 2)

MODIFY

energies[3] = “geothermal”

APPEND

energies.append(“nuclear”)

or

energies¬†+=¬†“nuclear”

COMBINE

energies¬†+= [“biomass”,¬†“hamster”]

COUNT

var lengthofArray = energies.count

LOGIC

var arrayIsEmpty = energies.isEmpty

REMOVE

energies.removeAtIndex(3)
energies.removeLast()
energies.removeAll(keepCapacity: true)
MUTATE
If we used let energies, then our array is immutable, vs if we used var energies which means its mutable.
Easy as pie.
DICTIONARIES

var energies = [

¬† ¬†¬†“Solar”:¬†“Thermal”,
¬† ¬†¬†“Photovoltaic”¬†:¬†“Grid”,
¬† ¬†¬†“Nuclear”¬†:¬†“Dangerous”
]
Here our keys are Solar, Photovoltaic & Nuclear.  These keys can be strings or numeric values such as integers.
Once again we can:
READ
let¬†cheapestSolarEnergy =¬†energies[“Solar”]
COUNT
var energiesCount = energies.count
MODIFY
energies[“Solar”] =¬†“PV”
REMOVE
energies[“Nuclear”] =¬†nil;
INSERT
energies[“Geo”] =¬†“Thermal”
and of course the value of a key can be an array or another dictionary:

var typesOfEnergy =

[
¬† ¬† platforms[“Solar”]: [“Thermal”,¬†“PV”,¬†“GridTied”],
¬† ¬† platforms[“Wind”]: [“Autonomous”,¬†“GridTied”],
¬† ¬† platforms[“Nuclear”] : [“Fusion”,¬†“Fission”,“Meltdown”]
]
and we would read it:
var type1 = typesOfEnergy[“Solar”][0]
See you next time! ūüôā

First SWIFT Tutorial ever! :-)

let is used for assigning constants whereas var is used for creating variables.

ie:

let ¬†salute: Character = “Hey there…”

let everyone: Character = “Swift¬†World”

var saluteEveryone = salute + everyone

saluteEveryone = saluteEveryone + “!”