xcode 元组类型 '(key: String, value: AnyObject)' 的值没有成员 'subscript'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47282796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 10:26:17  来源:igfitidea点击:

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

jsonswiftxcode

提问by Belal Elsiesy

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

我收到这样的错误:元组类型“(键:字符串,值:AnyObject)”的值没有成员“下标”

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.

我试图在线搜索但我不明白,它总是说一些关于将其更改为字典数组的内容,但是当我将数据解析为 [[String:AnyObject]] 时,它给了我一个错误。

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


`

回答by FuzzzzyBoy

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:

来自 Apple 文档:您可以使用 for-in 循环迭代字典中的键值对。字典中的每一项都作为 (key, value) 元组返回,作为迭代的一部分,您可以将元组的成员分解为临时常量或变量:

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

并注意您的代码的另一个问题:1) 函数 getLocation() 中有异步代码,当您在 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"

2) Swift 4 具有解析 JSON 的有用功能,研究一下。现在你得到的字典只有一个键值对,键等于“结果”

回答by ttt

I just ran into this error while trying to sort an array of Tuples. The reason is that Tuple members aren't referenced like Arrays.

我在尝试对元组数组进行排序时遇到了这个错误。原因是元组成员不像数组那样被引用。

For a Tuple you use location.latitude

对于您使用的元组 location.latitude

(For an Array you would use location["latitude"])

(对于您将使用的数组location["latitude"]

Tuples are declared with regular braces, not the square braces for arrays:

元组用普通大括号声明,而不是数组的方括号:

let location = (latitude: 2.3, longitude: 1.2)

let c = location.latitude   // c is now 2.3

I know the question is old, but I hope this helps anyone else searching for has no member 'subscript'

我知道这个问题很老,但我希望这可以帮助其他人搜索没有成员“下标”