Jason Leach
Jason Leach

Reputation: 4229

What does the ? mean in a downcast in Swift?

In the line:

 let x = cat.nameOfCat as? String

Does the ? after as mean that the downcast String is optional because if the casting fails, you'll end up with nil?

Upvotes: 0

Views: 185

Answers (1)

Catfish_Man
Catfish_Man

Reputation: 41801

With 'as?' if the object can't be cast, then it returns nil, while with 'as', if the object can't be cast than it crashes.

Use the ? form unless you're very sure that the cast is valid, in which case you can drop it to avoid dealing with the unnecessary optional.

Upvotes: 3

Related Questions