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.

No comments:

Post a Comment