Sunday, February 28, 2016

Swift Tutorial - Part 3 - Playground, enum, Optional, casting

Playground, enum, Optional, cast


Video Description

Playground

Swift has a very cool feature that allows you to write a code and get a quick result at the right side of the screen. In order to make a Playground file you should open the Xcode. From the left hand side of the screen select "Get started with a playground". From the opening window add a name for your file and choose the platform you want to code (for this tutorial select iOS) and then give it a location to save. t opens a blank page that you can write your code there. In order to test the playground, copy paste the code that we wrote in previous tutorial.

enum

There are 3 categories that we can code in Swift (class, struct and enum). One of the categories are called enum. Here is how we define enum in swift:

enum Gender {
    case Male
    case Female
}

Then we can use it like bellow:
var huxTek: Gender
huxTek = Gender.Male

We can alsowrite only .Male like this:
huxTek = .Male

we can have a switch for this enum like bellow:
switch huxTek {
    case .Male:
        print("A man")
    case .Female:
        print("A woman")
}
Optional !?

One of the important subjects that you should get familiar early in the game is optional type. You gonna see optional type in many place and actually you will use it a lot during  swift programming. That's why I dedicated a separate session just for Optional type.

Optional is just an enum with 2 cases like bellow:
enum Optional{
    case None
    case Some(T)
}
One case is none or null and the other case is something and something could be any type (String, Array, Int, ...). In order to explain it in an example, lets define a dictionary.
var myDict = [String:String]()
myDict = [
    "key1": "val1",
    "key2": "val2",
    "key3": "val3"
]
print(myDict["key1"])
The output of the above code is:
"Optional("val1")\n"

Unwrap Optional !

The reason that we have the word Optional around the val1 is because myDict["key1"] returns an optional. It means that it could have some value or nil. In order to unwrap the optional you should put ! after the optional value like bellow:
print(myDict["key1"]!)
The output of the above code is:
"val1"\n
Optional binding

In order to assign an optional type into a variable safely we should use the following pattern:
if let key1Val = myDict["key1"] {
    print(key1Val)
}
Cast
Imagine our dictionary includes key as String and value as String or another dictionary. The way we define it is like bellow. Since we don't know if it's String or a dictionary we just use a type called AnyObject. It means any type. 

var myDict = [String:AnyObject]()
myDict = [
    "key1": ["subKey1":"subVal1"],
    "key2": ["dasda", "asdasd"],
    "key3": "val3"
]
If we define a variable to get "key1" value, it returns the type as AnyObject because it doesn't know the type. In order to define a type for it we need to cast it like bellow:
    var sub1Key1Value = myDict["key1"] as! [String:String]
Now it knows that the type is a dictionary with key as String and value as String. In order to safely check if an object is a certain type we can use "is" function as bellow: 
if myDict["key1"] is [String:String] {
    var sub1Key1Value = myDict["key1"] as! [String:String]
    print(sub1Key1Value["subKey1"]!)
}
?
We have learned how to unwrap optional into a type, now we need to know how to define an optional type. It's very easy, you just have to add a question mark after the type of the variable.
var myString: String?
It's very important to know that after we put question mark, the variable is no longer a String type. It's type optional that could be String. In order to print it out we need to unwap it with ! 

Sunday, February 7, 2016

Swift Tutorial - Part 2 - Swift Foundation Frameworks

Swift Foundation Frameworks


Video Description

var

In order to define a variable in swift we use var at the beginning of the variable then the name of the variable and at the end we define the type of the variable like bellow:
var myVariable:String = "Some String Value"

let

If the value of a variable doesn't change during it's life cycle, we should use let instead of var, otherwise compiler would show warning. We define a variable with let like bellow: 
var myVariable:String = "Some String Value"

print

In order to print on console we can use print function in swift, here is the example:
print("This text will be printed in console after running the application")

String

From the name of this class it's obvious that it's for defining strings. Here is an example:
var myVariable:String = "Some String Value"

Double

let version: Double = 1.0
print(version)

Int

let myInteger: Int = 2
print(myInteger)

Bool

let isAwesome: Bool = true
print(isAwesome)

Array

We have 2 ways to define an array, here is the first one:


var letters = Array<String>()
letters = ["a", "b", "c", "d"]
print(letters[2])

The second way is to just define it like bellow:



var letters = ["a", "b", "c", "d"]
print(letters[2])

We can iterate the array objects like bellow:


var numbers = [Int]()
numbers = [1, 2, 3, 4]
        
for number in numbers {
   print(number)
}

Dictionary

We have 2 ways to define a dictionary, here is the first one:
var dict = Dictionary<String, Int>()
dict = ["One": 1, "Two":2]

The second way is to just define it like bellow:
var dict = [String:Int]()

We can iterate through keys and values of a dictionary like bellow:
for (key, value) in dict {
   print("Value for \(key) is \(value)")
}

NSObject, NSNumber, NSData, NSDate

These classes are inherited from Objective-c language and we will talk about them later