Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Casting in swift

Tags:

casting

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.

like image 606
Ranbijay Avatar asked May 13 '26 19:05

Ranbijay


1 Answers

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 {
   //...
}
like image 146
user1419265 Avatar answered May 16 '26 10:05

user1419265



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!