In my understanding, if AS can succeed, it means as? And the as! It will succeed. This is true in most cases, but there is always an exception. See the code below, I don’t know if you can see the problem.

Print (4 as Double) // print 4.0 print(4 as Double! Double) // crashCopy the code

The first line of code executes successfully, but the second line of code has the compiler ⚠️ and causes a crash. Why? And the reason for that is as and AS, right? With the as! The execution mechanism is different. As is executed at compile time, whereas AS? And the as! Is executed at runtime.

As that executes at compile time

Because as is executed at compile time, and at compile time, 4 is still a literal and has not been assigned an Int, it will succeed. 4 as Double is equivalent to the following code.

let x = 4 as Double
let x: Double = 4
Copy the code

As? Implemented at runtime With the as!

When the program is already running, 4 in the above code is already assigned an Int, so when you execute the second line of code, you will crash because it is not allowed to convert an Int to a Double.

as? And the as! The operation results are equivalent, the only difference being that if the transition fails, as! Would crash, as? Don’t.