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.
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.
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 {
//...
}
var button = somebutton as UIButton
and it was throwing an error. –
Lebar is
is used to check the type of a value whereas as
is used to cast a value to a different type.
The conditional form, as?
, returns an optional value of the type you are trying to downcast to.
Example:
let number: Int = 1
if number as? Int {
print ("Int")
}
You are "asking" if number is of type Int.
Using the as!
you're forcing, for example, your let number to be of a certain type, in case it is not, a crash you're going to take!
Example:
if number as! String { //CRASH
}
Answer in simple words ->
as! -> it is used for casting one data type to other data type forcefully(Use this only if you are sure..). We even call it force downcast means we downcast a particular type from superclass to subclass.
as -> This keywprd is used to raise an object to superclass type. So in other words we can say its upcasting.
as? -> So in this case unless you are certain that this cast is going to work then better option to add ? instead of !. Its also downcasting.
© 2022 - 2024 — McMap. All rights reserved.
as
is used for casting when it is guaranteed to succeed (String to NSString, [AnyObject] to NSArray, etc.) – Bridgetbridgetownas!
is used if it cannot be guaranteed. – Bridgetbridgetown