Noob Swift frustration with dicts and optionals
Noob Swift frustration with dicts and optionals
- Subject: Noob Swift frustration with dicts and optionals
- From: Jens Alfke <email@hidden>
- Date: Wed, 17 Sep 2014 09:58:12 -0700
Could someone explain this weird Swift error to me? I've figured out how to get around it, but I'd like to understand why it's occurring, since the description makes no sense to me. (The larger context of this is some code that extracts values from an NSDictionary parsed from JSON, carefully using optionals to avoid crashing on invalid input data.)
Here's an actual playground you can try out:
import Foundation var dict = [NSObject:AnyObject]() dict["foo"] = "bar"
let val = dict["foo"] // result is {Some "bar"} let val2 = val as? String // result is {Some "bar"}
let val3 = dict["foo"]? as? String // <—error
The error is "Operand of postfix '?' should have optional type; type is '(NSObject, AnyObject)'
I don't understand why this fails, since that line is really just a combination of the two previous lines merged into one statement. Also, the type of `dict["foo"]` _is too_ an optional, as shown in the results column of the playground. And where did the tuple mentioned in the error come from?
The utterly unintuitive fix is to change 'String' in the last line to 'NSString'. Then it compiles and produces the expected result. WTF?!?
|
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden