Monday, August 22, 2016

as and as? In Swift

Use the as operator if you are sure that the downcasting will always
succeed, because the as operator will trigger runtime error if the downcasting
fails. 

Use the as? operator when you are not sure if the downcasting will succeed
because it will return optional value, which means that you will receive nil if the

downcasting failed.

for view in subViews
{
     if view is UILabel // (Method 1)
    {
        let label = view as UILabel
        label.text = "bla bla bla"
    }

   if let button = view as? UIButton // (Method 2)
   {
      button.titleLabel?.text = "button"
   }
}

in method 1, we used the as operator because
we are sure that the view variable will be UILabel after we have checked its type
using the is operator. 

in method 2, we use the as? operator and the condition
will be true only if the casting succeeds and gives a non nil value.

DownCasting & UpCasting


Merubah (Cast) dari superClass ke variabel subclass dikenal dengan DownCasting.

Merubah (Cast) dari subClass ke variabel superClass dikenal dengan UpCasting.

Contoh :

DownCasting

Object employee = New Karyawan()
Karyawan buruh = (Karyawan) employee

Animal anim = new Cat();
Dog dog = (Dog) anim;


UpCasting

Dog dog = new Dog();
Animal anim = (Animal) dog;