Search code examples
swiftsubscript

Ambiguous use of 'subscript' Swift 3 compile error


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)
                }
            }
        }

Solution

  • 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) { ...