Thursday, June 12, 2014

Swift In Depth - Day I

The convention of printing a "Hello World" message is just one line in swift which is below 

println("hello world")

One difference to notice is that there is no semi colon. Also in swift line of code is a complete program! . one need not import a separate library for functionality like input/output or string handling. Code written at a global scope is considered as entry point for the program. so we don't need main also! 

We need to use let to make a constant and var to make a variable. The value of a constant doesn't need to be known at compile time. but we can assign the value only once. 

var myvariable = 43
myvariable = 45
let myconstant = 50

Providing the value at the initial time will let the compiler infer the type of the variable. However it is also possible to specify the type as part of the declaration 
for e.g. let explicitDouble: Double = 70 will tell that the constant explicitDouble is a Double type. 

let apples = 3
let oranges = 4
let appleSummary = "I have (apples) apples"
let fruitSummary = "I have (apples+oranges) pieces of fruit"

arrays and dictionaries use brackets. e.g. like below 

var animals = ["cat","mat","rat"]
animals[1] = "pussy cat"

var occupations = [ 
"steve" : "manager", 
"mary" : "speaker",
"taylor" : "cricketer",
]

occupations["marshal"]  = "guide"

Empty array and dictionary can be created in this following way:

let emptyArray = String[] ()
let emptyDict = Dictionary ()

Control Flow 

Control flow is using switch or if, and loop is using for in, for, while and do-while 
let individualScores = [75, 85, 103, 87, 12]
var teamscore = 0 
for score in individualScores 
{
if (score > 50)
{
teamScrore += 3
}
else 
{
teamscore += 1
}
}


in a condition statement, the expression must be a boolean variable. it cannot have if (score), instead, it should be if (score == 0 )

No comments:

Post a Comment