Why are there as
vs. as!
vs. as?
type casting in Swift ?
Asked
Active
Viewed 585 times
1

Maxim Veksler
- 29,272
- 38
- 131
- 151
-
possible duplicate of [Downcasting optionals in Swift: as? Type, or as! Type?](http://stackoverflow.com/questions/25708649/downcasting-optionals-in-swift-as-type-or-as-type) or http://stackoverflow.com/q/29637974/2792531 or http://stackoverflow.com/q/29674986/2792531 – nhgrif Jul 03 '15 at 23:40
-
I can't agree, I've reviewed all the above questions before posting, to my preference none speaks of the 3 various operations in a concise clear and easy to understand way. I've made this question to be as clear as possible coupled with demo code for future seekers, and as such I wouldn't call it a duplicate. – Maxim Veksler Jul 04 '15 at 16:20
1 Answers
6
as
is compile time cast
as?
and as!
are runtime casts
as?
will cast, if cast not possible will return Optional(nil)as!
will cast, if cast not possible will crash with runtime error
Example:
class Music { }
class Pop: Music { }
class Rock: Music { }
Pop() as Music // OK, some might disagree but Music *is* a super class of Pop
Pop() as Rock // Compile error: 'Pop' is not convertable to 'Rock'
let pop: AnyObject = Pop()
pop as Music // Compile error: 'AnyObject' is not convertible to 'Music'
pop as? Pop // Pop
pop as! Pop // Pop
pop as? Music // Pop
pop as! Music // Pop
pop as? Rock // nil
pop as! Rock // Runtime error signal SIGABRT

Maxim Veksler
- 29,272
- 38
- 131
- 151
-
I wouldn't call `as?` forced. `as?` is optional. `as` and `as!` are forced, `as` is safe, `as!` is not safe. – nhgrif Jul 03 '15 at 23:34
-
@nhgrif I think you're right about the forced categorisation, i'll rewrite my answer. – Maxim Veksler Jul 03 '15 at 23:37