-1

Currently getting the error "Ambiguous use of 'subscript'" when only building on a real iPhone. Not having any problems when using the simulator. Here is my code:

    let url=URL(string:myUrl)
    do {
        let allContactsData = try Data(contentsOf: url!)
        let allContacts = try JSONSerialization.jsonObject(with: allContactsData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject]
        if let arrJSON = allContacts["data"] {
            for index in 0...arrJSON.count-1 {

                let aObject = arrJSON[index] as! [String : AnyObject]
                if(ChooseSubject.mineFagKoder.contains(aObject["subject"] as! String)){
                    ids.append(aObject["id"] as! String)
                    names.append(aObject["name"] as! String)
                    subjects.append(aObject["subject"] as! String)
                    descriptions.append(aObject["description"] as! String)
                    deadlines.append(aObject["deadline"] as! String)
                }
            }
        }
Hamish
  • 78,605
  • 19
  • 187
  • 280
Sondre Brekke
  • 11
  • 1
  • 2
  • I think the problem might come from [String : AnyObject]. I'm not a Swift expert, but with reading I got some informations about similar scenarios. Check this out http://stackoverflow.com/questions/33642059/ambiguous-use-of-subscript-in-swift or even http://stackoverflow.com/questions/33592699/ambiguous-use-of-subscript-xcode-7-1 –  Mar 17 '17 at 13:28
  • Which line exactly?`let aObject = arrJSON[index] as! [String : AnyObject]` I'd guess it's because you didn't told the compiler that `arrJSON` is an array, so you can't do `arrJSON[index]`. – Larme Mar 17 '17 at 13:30
  • This line: let aObject = arrJSON[index] as! [String : AnyObject]. How can I tell that arrJSON is an array? – Sondre Brekke Mar 17 '17 at 13:34

1 Answers1

1

First of all the JSON dictionary type in Swift 3 is [String:Any].

The ambiguous use reason is that the compiler doesn't know the type of allContacts["data"]. It's obviously an array but you need to tell the compiler. And please don't use the ugly C-style index based for loops in Swift at all. If you need index and object in a repeat loop use enumerated().

if let arrJSON = allContacts["data"] as? [[String : Any]] {
   for aObject in arrJSON {
       if ChooseSubject.mineFagKoder.contains(aObject["subject"] as! String) { ...
vadian
  • 274,689
  • 30
  • 353
  • 361