Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value of tuple type '(key: String, value: AnyObject)' has no member 'subscript'

Tags:

json

xcode

swift

I get an error like this : Value of tuple type '(key: String, value: AnyObject)' has no member 'subscript'

I tried to search online but I don't understand, it always says something about changing it to an array of dictionaries but when I parse the data as [[String:AnyObject]] it gives me an error.

Error Screenshot

Here is my code for context

`//
//  MapViewViewController.swift
//  On the Map!
//
//  Created by Belal Elsiesy on 11/13/17.
//  Copyright © 2017 Elsiesy Industries. All rights reserved.
//

import UIKit

import MapKit

class MapViewViewController: UIViewController, MKMapViewDelegate {

    @IBOutlet weak var MapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        getLocations()
        let appDelegate = UIApplication.shared.delegate as! AppDelegate

        let locations  = appDelegate.locationData
        var annotations = [MKPointAnnotation]()

        // When the array is complete, we add the annotations to the map.

        for location  in locations! {

            // Notice that the float values are being used to create CLLocationDegree values.
            // This is a version of the Double type.
            let lat = CLLocationDegrees(location["latitude"] as! Double)
            let long = CLLocationDegrees(location["longitude"] as! Double)

            // The lat and long are used to create a CLLocationCoordinates2D instance.
            let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)

            let first = location["firstName"] as! String
            let last = location["lastName"] as! String
            let mediaURL = location["mediaURL"] as! String

            // Here we create the annotation and set its coordiate, title, and subtitle properties
            let annotation = MKPointAnnotation()
            annotation.coordinate = coordinate
            annotation.title = "\(first) \(last)"
            annotation.subtitle = mediaURL

            // Finally we place the annotation in an array of annotations.
            annotations.append(annotation)
        }
        // When the array is complete, we add the annotations to the map.
        self.MapView.addAnnotations(annotations)
    }
}




    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
func getLocations() {

        var request = URLRequest(url: URL(string: "https://parse.udacity.com/parse/classes/StudentLocation")!)
        request.addValue("QrX47CA9cyuGewLdsL7o5Eb8iug6Em8ye0dnAbIr", forHTTPHeaderField: "X-Parse-Application-Id")
        request.addValue("QuWThTdiRmTux3YaDseUSEpUKo7aBYM737yKd4gY", forHTTPHeaderField: "X-Parse-REST-API-Key")
        let session = URLSession.shared
        let task = session.dataTask(with: request) { data, response, error in
            if error != nil { // Handle error...
                ////////////////////////DO THIS LATER
            }
            print(String(data: data!, encoding: .utf8)!)
        let parsedResult: [String:AnyObject]!
            do {
                parsedResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as!  [String : AnyObject]


                let appDelegate = UIApplication.shared.delegate as! AppDelegate
                appDelegate.locationData = parsedResult
            } catch {
                print("Could not parse the data as JSON: '\(data)'")

            }


        }
        task.resume()
    }


`
like image 462
Belal Elsiesy Avatar asked Nov 28 '25 20:11

Belal Elsiesy


1 Answers

From Apple Documentation: You can iterate over the key-value pairs in a dictionary with a for-in loop. Each item in the dictionary is returned as a (key, value) tuple, and you can decompose the tuple’s members into temporary constants or variables as part of the iteration:

for (key, value) in dictionary {
    print(key)
    print(value)
}

And pay attention to another issue with your code: 1) There is async code in function getLocation() and when you assign in viewDidLoad()

let locations  = appDelegate.locationData

locations equal nil.

2) Swift 4 have useful features for parse JSON, research this. Now you get dictionary with only one key-value pair with key equal "result"

like image 76
FuzzzzyBoy Avatar answered Dec 01 '25 09:12

FuzzzzyBoy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!