Type 'Any' has no subscript

This is my struct :

struct LocationDemo {
    var name : String?
    var type : Array<Any>?
    var coordinates : Array<Any>?
    
    subscript(index: Int) -> Any {
        
        return(coordinates)! 
    }
    
}

this is my swiftyJson script :

 for i in 0 ..< json.count {
     james = LocationDemo(name: json[i]["name"].stringValue, type: json[i]["location"].arrayValue.map({$0["type"].stringValue}), coordinates: json[i]["location"].arrayValue.map({$0["coordinates"].arrayValue}))
                    
     locationArray.append(james)
 }

And i keep getting in error when i run this code :

locationArray[0].coordinates?[0][0]

And the reason why i have two subscripts (coordinates?[0][0]) because coordinates is an array within an array and I’m trying to get the coordinates within it. Any help will be appreciated.

Hi @ghost6ix! Could you possibly share an example of the JSON that you are attempting to parse? I think there are more cleaner and safer ways to parse this but its hard to work it out from the code example above.

Also, what are you trying to subscript on your struct as you do nothing with the index value :thinking:

Your coordinates are almost guaranteed to be of type Double, so instead of Array you should say [Double] instead. The bracketed syntax is preferred over Array syntax.

Your [0][0] would be an array of array, which isn’t what you’ve got. You have an array with two elements, right? So you’d want to access it as …coordinates?[0] and …coordinates?[1] So you probably want:

if let coordinates = locationArray[0].coordinates {
let latitude = coordinates[0]
let longitude = coordinates[1]
}

This topic was automatically closed after 166 days. New replies are no longer allowed.