1

Does the as! unwrap what ever is before it like

var a = value as! Double 

the a is not an optional

where

var a = value as? Double

the a is optional Double?

Lightsout
  • 3,454
  • 2
  • 36
  • 65

1 Answers1

4

as? produces an optional value, which is either the value if it can be cast to the specified type, or nil if it can't.

as! doesn't produce an optional, it just produces a value of the specified type, and if the cast fails, it aborts the program. Saying foo as! SomeType is basically the same thing as saying (foo as? SomeType)! (except you get a better error message).

You should only ever use as! if you're 100% certain the cast will succeed (because if you're wrong, the whole program aborts).

Lily Ballard
  • 182,031
  • 33
  • 381
  • 347