I've been playing around with Swift and discovered that when down casting an object to be inserted into a dictionary, I get a weird warning: Treating a forced downcast to 'String' as optional will never produce 'nil'
. If I replace as
with as?
then the warning goes away.
func test() -> AnyObject! {
return "Hi!"
}
var dict = Dictionary<String,String>()
dict["test"]=test() as String
Apple's documentation says the following
Because downcasting can fail, the type cast operator comes in two different forms. The optional form,
as?
, returns an optional value of the type you are trying to downcast to. The forced form,as
, attempts the downcast and force-unwraps the result as a single compound action.
I'm unclear as to why using as?
instead of as
is correct here. Some testing reveals that if I change test() to return an Int instead of a String, the code will quit with an error if I continue using as
. If I switch to using as?
then the code will continue execution normally and skip that statement (dict will remain empty). However, I'm not sure why this is preferable. In my opinion, I would rather the program quit with an error and let me know that the cast was unsuccessful then simply ignore the erroneous statement and keep executing.
According to the documentation, I should use the forced form "only when you are sure that the downcast will always succeed." In this case I am sure that the downcast will always succeed since I know test()
can only return a String so I would assume this is a perfect situation for the forced form of down casting. So why is the compiler giving me a warning?
import Foundation
, it wouldn't even compile, becauseString
is not a class type and is not compatible withAnyObject
. If you change the lastString
toNSString
, the warning goes away, meaning probably that it is an issue with you usingString
, a non-class type, in theas
. – Anseas
have been removed, and been replaced withas!
. So you you will get the same error when you useas!
(usingas
will not generate this error anymore) – Contravallation