I believe it has something to do with optionals, but I'm safely unwrapping sourceURL so I'm still not sure where the error is! I'm trying to access a JSON object's array's dictionary value.
However, I'm still getting the "could not find overload for 'subscript' that accepts the supplied arguments.
It seems simple, but I just can't seem to figure it out!
var dictTemp: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &localError) as? NSDictionary
var finalURL: String
// error line below
if let sourceURL = dictTemp[0]["source"]["sourceUrl"] as? NSString {
finalURL = sourceURL as String
}
NSDictionary accessed from Swift is an interesting beast.
As long as Swift only knows something is an NSDictionary (not a more specific
[Key: Value]
Swift-style dictionary), you can only retrieveAnyObject?
s out of it.But then, since you've imported Foundation, you can keep going with a magical subscript operator that works on
AnyObject
, and checks whether the thing is a dictionary:Here's where it gets interesting, because
step1
was a dictionary with a "source" key inside it,step2
will be the corresponding value.step1
was a dictionary without a "source" key,step2
will benil
— in particular, it'sAnyObject??.Some(AnyObject?.None)
.step1
was nil (the original dictionary didn't have 0 as a key), or not a dictionary (it had a 0 key with some other kind of value), thenstep2
will benil
— in particular,AnyObject??.None
.(The distinction between the last 2 cases is mostly unimportant and you shouldn't worry about it, but if you're interested you can see it by using
dump
).And of course, we can apply the same principle again:
Now, binding them all in one
if
:Caveat
This type of syntax can be dangerous, since it works with arrays and dictionaries at the same time. What would you expect in these situations?