I'm trying to understand of as
typecasting.
Reading Type Casting chapter on Apple Documentation, I've two syntax for downcasting (as? and as! operators) but I didn't find anything about as
.
So I thought that I should never have used this kink of operator but yesterday when I was typing code with do-try-catch
statement, I met this one:
catch let error as NSError {
print(error)
}
Initially, error was type conforms to the Error protocol
.
Now using the as NSError
casting, it has become an instance of a NSError
class.
But my question is: What does as operator do? It's not a downcasting sure.. Could it be used for "convert" object?
EDIT
I don't think it's a duplicate.
In my case, the error variable, is not a class and doesn't inherit from a super class so I have not a upcasting. It is not even a pattern matching
.
I've already read both Swift Blog page and this thread on StackOverflow.
EDIT 2 From Swift Blog
Swift 1.2 separates the notions of guaranteed conversion and forced conversion into two distinct operators. Guaranteed conversion is still performed with the as operator, but forced conversion now uses the as! operator. The ! is meant to indicate that the conversion may fail. This way, you know at a glance which conversions may cause the program to crash.
The text above doesn't work for me because if I tried to use the as!
operator instead of as
, compiler complain me.
EDIT 3
Even in Using Swift with Cocoa and Obj-C documentation they use the let-as?
syntax for checking and casting to a protocol.
So, why in my case, I can't use it?