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?
First of all, as suggested in the dasblinkenlight's comment, your code snippet is not using a type-casting-operator. Check the syntax of do-statement and you can find these:
So, your EDIT 2 has no meaning, there are no syntax accepting
as!
in catch-clause.But this code (using type-casting-operator) works, so I try to explain how to use
as
-casting.As shown in the linked article in the EI Captain v2.0's comment,
as
-casting is used for Guaranteed conversion. I have collected some use cases of such conversions.Upcasting
As shown in the article, upcasting always succeeds, so you can use
as
.Specifying literal type
In Swift, literals are typeless, so you can use
as
to specify the types of literalsIn case Swift can infer the type of the literal, you can omit such
as
-casting:Disambiguating overloaded methods
Always-succeeds bridging
The example
let nsError = error as NSError
is included in this category, and you need to read this article carefully, to understand why this is an always-succeeds bridging.For your EDIT 3.
You may need to distinguish these two syntaxes:
As already noted,
catch
leads a pattern, and you cannot useas?
in pattern.