Ambiguous reference to member subscript in Alamofi

2019-07-29 15:23发布

Alamofire.request(videosUrl!).responseJSON { response in
        if response.result.value != nil {

            let json = response.data

            do {

                let readableJSON = try JSONSerialization.jsonObject(with: json!, options: .mutableContainers) as? JSONStandard

                if let items = readableJSON {

                    for i in 0..<items.count {

                        let item = items[i] <<< ERROR HERE

                        ...REST OF CODE HERE
                    }
                }    

             } catch {
                 print(error)
             }
         }
     }

I also have a typealias set:

typealias JSONStandard = [String:AnyObject]

My question is why am I getting the 'Ambiguous reference to member subscript' error? All I am trying to do is access the correct part of the array.

1条回答
家丑人穷心不美
2楼-- · 2019-07-29 15:47

The error happens, because subscript method of Dictionary (which is yours JSONStandard) requires:

1) String as a key parameter, but you passing i which has Int type. And according to the example your code is based on you probably should replace

if let items = readableJSON {
...
}

with

if let tracks = readableJSON["tracks"] as? JSONStandard {
      if let items = tracks["items"] as? [JSONStandard] {
          ...
      }
}

In this case items becomes an Array which uses Int index in subscript method.

2) or because Dictionary is also a collection with index type DictionaryIndex<Key, Value> subscript also can expect DictionaryIndex<String, AnyObject>. In your case you can replace

for i in 0..<items.count {

with

for i in items.indices {

or even with

for (_, item) in items {

The solution you chose depends on the structure of your JSON

查看更多
登录 后发表回答