2

I have a problem similar to this question, but the answers there isn't helping me.

I have these lines of code:

var id = item["id"] as? String ?? ""
var name = item["name"] as? String ?? ""
var pic = item["pic"] as? String ?? ""

To me these lines of code a pretty much the same. For Xcode, this is a different matter.

The first line is fine. The second two lines generate this error:

'(key: AnyObject, value: AnyObject)' does not have a member named 'subscript'

Here is some more context for you all:

class func getFromJson(json:NSDictionary) -> [Collection] {
    var collections = [Collection]()
    if json.count > 0 {
        for item in json {
            var id = item["id"] as? String ?? ""
            var name = item["name"] as? String ?? ""
            var pic = item["pic"] as? String ?? ""
            var newUser = Collection(id:id, name:name, pic:pic)
            collections.append(newUser)
        }
    }
    return collections
}

Can anyone explain to me how to fix this. Bonus points if you can explain why the first line is fine, but the next two nearly identical lines produce errors!

Thanks in advance.

Community
  • 1
  • 1
Jimmery
  • 9,783
  • 25
  • 83
  • 157
  • The first line generates the same error message for me. But from your code it seems that the parameter should be `json: NSArray`, and then everything compiles just fine. – Martin R Nov 12 '14 at 15:51
  • @MartinR add this as an answer and I will mark you are correct. – Jimmery Nov 12 '14 at 16:16
  • I get the same error on all three lines in a Xcode 6.1 playground. – David Berry Nov 12 '14 at 16:19
  • Ive got 6.1 too - but this is in a class and not in the playground. I am starting to think that the first line not generating an error is just Xcode being glitchy... – Jimmery Nov 12 '14 at 16:27

1 Answers1

12

'(key: AnyObject, value: AnyObject)' indicates that item is not an Dictionary but is a Tuple with a single key/value pair.

Iterating dictionaries in swift interates through tuples:

for (key, value) in json {
    println(key, value)
}

Your for loop indicates that you are probably wanting a json Array of tuples instead of a json Dictionary.

item["id"] would give you a compile time error if you declared the parameter as a tuple. It seems you stumbled onto something hidden with the language with how either tuples or subscripts work under the hood.

More on Subscripts

More on Types (Tuples)

Krys Jurgowski
  • 2,871
  • 17
  • 25
  • The function declaration says he's expecting a dictionary. My guess is he's missing the step where he pulls the embedded array out of the dictionary. – David Berry Nov 12 '14 at 16:17