Reputation: 630
Is there a difference (and if so what's the underlying principle?) between downcasting variable as! NSString
and downcasting variable as NSString!
?
Upvotes: 0
Views: 1330
Reputation: 18191
What you are referring to is known better as downcasting. You can read Apple's documentation on this matter here.
A constant or variable of a certain class type may actually refer to an instance of a subclass behind the scenes. Where you believe this is the case, you can try to downcast to the subclass type with a type cast operator (as? or as!).
Because downcasting can fail, the type cast operator comes in two different forms. The conditional form, as?, returns an optional value of the type you are trying to downcast to. The forced form, as!, attempts the downcast and force-unwraps the result as a single compound action.
Use the conditional form of the type cast operator (as?) when you are not sure if the downcast will succeed. This form of the operator will always return an optional value, and the value will be nil if the downcast was not possible. This enables you to check for a successful downcast.
Use the forced form of the type cast operator (as!) only when you are sure that the downcast will always succeed. This form of the operator will trigger a runtime error if you try to downcast to an incorrect class type.
Upvotes: 1
Reputation: 3873
variable as! NSString
is forced downcasting of a variable to NSString
and will raise run time error if variable
is not NSString
.
variable as NSString!
Since Swift 1.2 operator as
can only be used for upcasting, so above code will raise compile time error, unless variable
is known to be a subclass of NSString
.
Upvotes: 4