Search code examples
swiftcasting

Type Casting in swift


I am bit confused with typecasting in Swift.

Have a small doubt. What is the difference between as?,as! and only as. And can we say "as" is similar to is.

Thanks in advance.


Solution

  • The 'as' keyword is used for casting.

    'as' example:

    let calcVC = destinationViewController as CalculatorViewController
    

    This line casts the destinationViewController to a CalculatorViewController. However, this would crash if destinationViewController was not a CalculatorViewController or a subclass thereof.

    To protect against a crash, you can use 'if let' with 'as?'...

    'as?' example:

    if let calcVC = destinationViewController as? CalculatorViewController {
       // ... write code to execute if destinationViewController is in fact a CalculatorViewController
    }
    

    You can even check before you even try to do 'as' with the 'is' keyword...

    'is' example:

    if destinationViewController is CalculatorViewController {
       //...
    }