Sunday, September 20, 2015

Essentials of Swift - Learning Part I

Basic Types: Swift uses let to make constants and var to make the variables. 

var myvariable = 42
let myconstant = 42

Every constants and variable has type in Swift. However, it is inferred and no need to be specified explicitly. 

If the initial value doesnt provide enough information (or if there is no initial value), specify the type by writing it after the variable, separated by semi colon. 

let explicitDouble : Double = 70

Values are never implicitly converted to another type. IF we need to convert a value to a different type, explicitly make an instance of desired type. Here, we are converting an int to String 

let label = “Width is”
let widthLabel = label + String (width)

We have an () & \ string interpolation way like below 

let apples = 3
let orange = 2
let apple summary = “i have \(apples) apples”
let fruitSummary = “i have \(apples+orange) fruits”

We can work with Optionals if the value may be missing. An optional value either contains a value or a nil to indicate the value may be missing. We need to write ? after the type of the value to indicate that it is optional. 

let optionalInt : Int? = 0

To get the underlying value form the optional, we just need to unwrap it. the ! is called forced unwrap operator. 

let actualInt: Int = optionalInt!

let myString = “7”
let myString2 = “one”

var possibleInt = Int(myString)
var possibleInt2 = Int(myString2)

print(possibleInt) 
print(possibleInt2)

the above will output as 7 and nil. 

Below is how we can declare an array 

var ratingList = {“poor”, “average”, “good”}
If we want to create an empty array, use the initialize syntax. 
let emptyArray = [String]()

References:

No comments:

Post a Comment